Java Reference
In-Depth Information
This example sets the pixel at (
10
,
10
) to
0x80ff0000
. You interpret this 32-bit
hexadecimalvalue(fromlefttoright)as50%translucency,brightred,nogreen,andno
blue.Becausethebufferedimagewascreatedas
TYPE_INT_RGB
,thealphacompon-
ent is ignored.
Youcanaccessapixel'svaluebyinvoking
int getRGB(int x, int y)
.The
following example returns the value stored at location (
10
,
10
):
int rgb = bi.getRGB(10, 10);
Note
Regardless of the buffered image's type, the
setRGB()
and
getRGB()
methodsalwaysaccessthebufferedimageasifitwascreatedinRGB/ARGBformat.
setRGB()
and
getRGB()
translate to or from the underlying format.
Anotherwaytopopulateabufferedimageistocreatean
Image
instanceanddraw
itsassociatedimageontothebufferedimageaftertheimagehasfullyloaded.Youcan
accomplish this task as follows:
Image
image
=
Toolkit.getDefaultToolkit().getImage("image.png");
MediaTracker mt = new MediaTracker(this); // this repres-
ents current component
mt.addImage(image, 1);
try { mt.waitForID(1); } catch (InterruptedException ie) {
assert false; }
BufferedImage bi = new BufferedImage(image.getWidth(null),
image.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics2D bg = bi.createGraphics();
bg.drawImage(image, 0, 0, null);
bg.dispose(); // Always dispose of a created Graphics2D
context.
I specified
TYPE_INT_ARGB
as the buffered image's type because PNG images
are associated with an alpha channel. Also, I passed
null
to
getWidth()
,
getHeight()
,and
drawImage()
becauseanimageobserverisn'trequiredafterthe
image is fully loaded.
BufferedImage
declares a
Graphics2D createGraphics()
method that
returnsa
Graphics2D
instanceforuseindrawingimagesorgraphicsonthebuffered
image. After you finish drawing, you must dispose of this context.