768 Part II: The Java Library
grabPixels( )is defined like this:
boolean grabPixels( )
throws InterruptedException
boolean grabPixels(longmilliseconds)
throws InterruptedException
Both methods returntrueif successful andfalseotherwise. In the second form,milliseconds
specifies how long the method will wait for the pixels. Both throwInterruptedExceptionif
execution is interrupted by another thread.
Here is an example that grabs the pixels from an image and then creates a histogram of
pixel brightness. Thehistogramis simply a count of pixels that are a certain brightness for all
brightness settings between 0 and 255. After the applet paints the image, it draws the histogram
over the top.
/*
* <applet code=HistoGrab.class width=341 height=400>
* <param name=img value=vermeer.jpg>
* </applet> */
import java.applet.*;
import java.awt.* ;
import java.awt.image.* ;
public class HistoGrab extends Applet {
Dimension d;
Image img;
int iw, ih;
int pixels[];
int w, h;
int hist[] = new int[256];
int max_hist = 0;
public void init() {
d = getSize();
w = d.width;
h = d.height;
try {
img = getImage(getDocumentBase(), getParameter("img"));
MediaTracker t = new MediaTracker(this);
t.addImage(img, 0);
t.waitForID(0);
iw = img.getWidth(null);
ih = img.getHeight(null);
pixels = new int[iw * ih];
PixelGrabber pg = new PixelGrabber(img, 0, 0, iw, ih,
pixels, 0, iw);
pg.grabPixels();
} catch (InterruptedException e) {
System.out.println("Interrupted");
return;
}