Java Reference
In-Depth Information
Figure 11.2 The
GrayBufImagePanel class
creates a gray scale
BufferedImage from a
pixel array.
int array large enough to hold the pixel data. The next to last parameter specifies
the offset into the pixel array where the filling should begin and the last parameter
is again the scan size.
To deal with other types of images, a little more work must be done. The
following GrayBufImagePanel class creates a byte array with values from 0
to 255 that represent gray levels. A BufferedImage of the TYPE - BYTE - GRAY
is created. To fill it with our byte array we need to get the raster for the image and
it must be a WritableRaster type that allows us to modify the pixels. This is
obtained with
WritableRaster wr = fBufferedImage.getRaster ();
Then the pixel data is set with
wr.setDataElements (0, 0, fWidth, fHeight, fPixels);
Figure 11.2 shows the resulting image.
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
/** Create a gray scale BufferedImage from a pixel array. **/
public class GrayBufImagePanel extends JPanel
{
BufferedImage fBufferedImage;
int fWidth = 0, fHeight = 0;
byte[] fPixels;
/** Build a BufferedImage from a pixel array. **/
void makeImage () {
fWidth = getSize ().width;
fHeight = getSize ().height;
fPixels = new byte [fWidth * fHeight];
// Create an array of pixels with varying gray values
int i = 0;
int half - width = fWidth/2;
 
Search WWH ::




Custom Search