Java Reference
In-Depth Information
Discussion
The imageio package provides java.awt.image.BufferedImage to represent an image in
memory. It's a subclass of java.awt.Image , so normal graphics methods can be applied to
it, starting with getGraphics() . The static ImageIO methods read() and write() can be
used to load and store a BufferedImage .
The program shown here uses these methods to create the original versions of the circled
6/7/8 images that are used throughout this topic to indicate the version of Java needed to run
a particular code fragment, starting with a single coffee cup image created by artist TikiGiki
and provided under the Creative Commons license from http://OpenClipArt.org .
The Font method getStringBounds() is similar to the FontMetrics object used in Draw-
ing Centered Text in a Component in that it measures the actual width of the characters being
drawn. This plus a bit of simple arithmetic lets us put the large black version number ( 6 in
this example) on top of the coffee cup, then we save the updated image to a file on disk;
these are included in the topic using the normal AsciiDoc image mechanism. Example 12-6
shows the complete code for generating the image.
Example 12-6. ReadWriteImage.java
int
int v = 6 ;
BufferedImage image = ImageIO . read ( new
new File ( dir + "coffeecup.png" ));
Graphics2D g = image . createGraphics ();
Font f = new
new Font ( "Serif" , Font . BOLD , 160 );
g . setFont ( f );
g . setColor ( Color . black );
String bigNumberLabel = Integer . toString ( v );
Rectangle2D lineMetrics =
f . getStringBounds ( bigNumberLabel , g . getFontRenderContext () );
int
int x = ( int
int ) (( image . getWidth () - lineMetrics . getWidth () ) / 2 );
x -= 10 ;
// ad-hoc fudge factor
int
int y = ( int
int ) (( image . getHeight () + lineMetrics . getHeight ()) / 2 );
g . drawString ( bigNumberLabel , x , y );
ImageIO . write ( image , "png" , new
new File ( String . format ( "%sjava%d.png" , dir , v )));
The code needs to end with System.exit(0); because the graphics code starts a background
thread.
See Also
The ImageIO tutorial describes the ImageIO library in more detail.
Search WWH ::




Custom Search