Wednesday, January 09, 2008

How to use PixelGrabber class to acquire pixel data from an Image object

PixelGrabber class available in java.awt.image packate can be used to access pixels of an Image object. PixelGrabber class can acquire pixel data synchronously or asynchronously. It can store pixel values in a user-specified array or create a suitable array itself.

The following example shows how to use PixelGrabber class to get pixel data from an Image object.

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;

public class PixelGrabberTest {

public PixelGrabberTest() {
}

public static void processImage(String inFile, String outFile) {

Image image = Toolkit.getDefaultToolkit().getImage(inFile);

try {

PixelGrabber grabber =
new PixelGrabber(image, 0, 0, -1, -1, false);

if (grabber.grabPixels()) {
int width = grabber.getWidth();
int height = grabber.getHeight();

if (isGreyscaleImage(grabber)) {
byte[] data = (byte[]) grabber.getPixels();

// Process greyscale image ...

}
else {
int[] data = (int[]) grabber.getPixels();

// Process Color image

}
}
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
}

public static final boolean isGreyscaleImage(PixelGrabber pg) {
return pg.getPixels() instanceof byte[];
}

public static void main(String args[]) {

if (args.length > 1) {
processImage(args[0], args[1]);
System.exit(0);
} else {
System.err.println(
"usage: java PixelGrabberTest ");

System.exit(2);
}

}
}

No comments: