Java Reference
In-Depth Information
Similarly, you can pack separate component values into an integer pixel variable:
int color
=
(alpha
<<
24)
|
(red
<<
16)
|
(green
<<
8)
|
blue;
The alpha, or transparency, factor is used when an image is overlaid on a back-
ground color or another image. This can be useful for various situations such
as when placing an icon on a button. For example, you may want to allow the
background color of the button to show through the blank areas of the icon.
11.8.2
PixelGrabber
The
Image
class does not offer direct access to its pixel array. Instead, you use the
class
java.awt.image.PixelGrabber
,which, as its name implies, grabs
the pixel data for you. The following code shows how to put the pixel values of
an image into an array:
...
int[] pixels = new int[width * height];
boolean got
-
pixels = false;
PixelGrabber grabber =
new PixelGrabber (img, x0, y0, width, height, pixels, 0,
scan
-
Width);
try {
grabber.grabPixels ();
}
catch (InterruptedException e)
{
got
-
pixels
=
false;
return;
}
if ((grabber.getStatus () & ImageObserver.ALLBITS)!
=
0)
{
got
-
pixels
=
false;
return;
}
First an array big enough to hold the pixels is created. The first parameter of the
PixelGrabber
constructor is the image reference. The pixels to be grabbed
come from a rectangular section of the image as specified by the top left corner
at
(x0, y0)
and by the width and height parameters. The pixel array reference
is passed in the next parameter, and the last two parameters include an offset
into the array to indicate where to begin putting the pixels (here set to 0) and the
scan
-
Width
value, which specifies the number of pixels per row. To capture a
whole image in the
pixels
array, set the
x0, y0
values to zero, use the
width,
height
for the image and set
scan
-
Width
equal to the image width.
Search WWH ::
Custom Search