Thursday, June 26, 2008

Building Your Own Image Loader

Images Needed
When programming games images are one of the things that just comes pretty standard. Whether its textures for 3D models, 2D background images, or even sprite sheets. There are a variety of formats for image files here are just a few, jpg (jpeg), gif, tga, pcx, png, and bmp. Some of the formats are compressed jpg & gif for example but their compression comes at the cost of accuracy. If you save an image in paint in either of these formats then reopen it you will see that the pixels color changed slightly. The bmp format or bitmap is uncompressed thus taking up a lot of space. The best format for both accuracy and compression is png. So for pretty much any graphics in game programming they tend to be used more often then not. Another nicety is pngs support an alpha channel useful for not fully transparent images.

Common ways of Loading Images
The most common way that I've seen to load images in Java is by using ImageIcon. It was also the first that I learned. It's very simple.
//substitute myImagePath for the relative or absolute path and file name
Image img = (new ImageIcon(myImagePath)).getImage();
AWT Toolkit provides another way of loading images
//substitute myImagePath for the relative or absolute path and file name
java.awt.Toolkit awtkit = Toolkit.getDefaultToolkit();

//this method might cause memory issues
Image img = awtkit.getImage(myImagePath);
//recommended to use this instead.
img = awtkit.createImage(myImagePath);
These two methods are about all you really need to load images. But both of these methods do not load BufferedImages but rather only images. I believe they are VolitileImages.

There is a third alternative for image loading javax.imageio package contains a ImageIO class that can be used to load BufferedImages.
//Load a buffered image.
BufferedImage bImg = ImageIO.read(myImagePath);
This class is useful because it provides a means of loading a buffered image. The use for a buffered image is that it provides a way to extract parts of the image itself as separate images which is very useful for sprite sheets and tilesets.


The Loader
The basics of a loader is to hold on to images that are currently loaded. There are many advantages to using an image loader. You can detect when an OutOfMemoryError occurs and release existing images to free memory. You can load arrays of BufferedImages or whole directories even load all resources in a given directory and its subdirectories.

One of the extremely useful things about a loader is you can configure it to load images from inside a jar file. Which I will explain how to do later?

No comments:

Post a Comment