Chapter 25: Images 767
The data for the newMemoryImageSourceis created in theinit( )method. An array of
integers is created to hold the pixel values; the data is generated in the nestedforloops where
ther,g, andbvalues get shifted into a pixel in thepixelsarray. Finally,createImage( )is called
with a new instance of aMemoryImageSourcecreated from the raw pixel data as its parameter.
Figure 25-4 shows the image when we run the applet. (It looks much nicer in color.)
ImageConsumer
ImageConsumeris an abstract interface for objects that want to take pixel data from images
and supply it as another kind of data. This, obviously, is the opposite ofImageProducer,
described earlier. An object that implements theImageConsumerinterface is going to create
intorbytearrays that represent pixels from anImageobject. We will examine thePixelGrabber
class, which is a simple implementation of theImageConsumerinterface.
PixelGrabber
ThePixelGrabberclass is defined withinjava.lang.image. It is the inverse of the
MemoryImageSourceclass. Rather than constructing an image from an array of pixel
values, it takes an existing image andgrabsthe pixel array from it. To usePixelGrabber,
you first create an array ofints big enough to hold the pixel data, and then you create a
PixelGrabberinstance passing in the rectangle that you want to grab. Finally, you call
grabPixels( )on that instance.
ThePixelGrabberconstructor that is used in this chapter is shown here:
PixelGrabber(ImageimgObj, intleft, inttop, intwidth, intheight, intpixel[ ],
intoffset, intscanLineWidth)
Here,imgObjis the object whose pixels are being grabbed. The values ofleftandtopspecify
the upper-left corner of the rectangle, andwidthandheightspecify the dimensions of the
rectangle from which the pixels will be obtained. The pixels will be stored inpixelbeginning
atoffset.The width of a scan line (which is often the same as the width of the image) is passed
inscanLineWidth.
FIGURE 25-4
Sample output from
MemoryImageGenerator