11.6. A PNG Decoder

One reason you might have to know the internal anatomy of BufferedImage is if you intend to create images from data contained in files. In this section, I'll present classes that create a BufferedImage from information contained in a Portable Network Graphics (PNG) file.[5] PNG supports many image formats and color depths. This example will load only PNG images with a palette (i.e., only those with indexed color). I won't attempt to describe the PNG format in any detail. If you're interested, a lot more information is available at http://www.simtel.net. If you'd like to learn more about many different file formats, take a look at the Encyclopedia of Graphics File Formats, Second Edition , by James D. Murray and William vanRyper (O'Reilly).

[5] The other interpretation of PNG is "PNG is Not GIF." The GIF standard, while popular, has some significant shortcomings. First, it uses LZW compression technology, which is not entirely free; you may need to buy a license in order to write and distribute a GIF encoder or decoder. Furthermore, GIF's maximum color depth is eight bits, which is insufficient for many applications.

This example is comprised of three classes. PNGDecoder knows the overall layout of a PNG file and handles the details of loading each part, or chunk, of the file. It also includes a main() method that will load a PNG file and show it in a frame window. The second class, PNGChunk, represents a single chunk of data from the file. The last class is ...

Get Java 2D Graphics now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.