Java tips: Tap into the AWT Image class and FileNameMap

Need some Java tips you can put to work right away? Here are a couple of techniques you'll want to pick up if you work with Graphics objects or MIME files in Java.

If you work with graphics in Java, these two tips will come in handy. The first dives into the Java Abstract Windows Toolkit (AWT). The second offers advice on working with Multipurpose Internet Mail Extensions (MIME) file types and explains how some hidden mapping makes this easier.

Use Java AWT to convert Graphics to Image objects
The AWT provides many methods to draw onto Graphics objects, but how do you draw onto an Image object or convert a Graphics object to an Image object?

The AWT Image class provides a getGraphics method, and its extension, the BufferedImage class, provides a createGraphics method. The preference is to use a BufferedImage, as this returns the more powerful Graphics2D class. Check out the code snippet below:
BufferedImage bffImg = new BufferedImage( );
Graphics gfx = bffImg.createGraphics( );
gfx.drawRect(10, 10, 50, 20);  // draw a rectangle

BufferedImage enables developers to create their own images using the powerful Graphics API and then write it to disk or return it to a client in the form of a PNG or GIF. The new JDK 1.4 provides an API that allows this image encoding. For those of us still using 1.3 and before, there is the Java Advanced Imaging (JAI) API.

You can use this technique to create a snapshot of any component, be it Swing or AWT, and save it to an image. This would be one way you could create screen shots. Please note that the component in question must be drawable, so you must add it to some invisible, onscreen container. The open source utility library from nanoTITAN Inc. has such a snapshot method in its ComponentUtility class.

Discover MIME type
When returning content from a servlet or JavaServer Page (JSP) other than HTML, you need to know the MIME type. Often, you have to hard-code the information—but is there a better way?

Although it doesn't support all the types you're likely to need, Java does provide automatic filename-to-MIME type mapping. The mapping is hidden within an interface called FileNameMap, which you can find in the package. The map is obtained via the URLConnection class, which is in the same package. Once the map is obtained, getContentTypeFor is the only method available. By passing in a filename, the MIME type for that extension can be determined.

Listing A offers some simple example code, which returns the following values (note that not all file extensions are known):


Working with graphics and images in Java can be a challenge, but the AWT and the FileNameMap interface help make it easier.

Hey, buddy, can you spare a Java tip?
If you'd like to share a Java tip, contact the editors.



Editor's Picks