Previous | Next | Trail Map | Creating a User Interface | Working with Graphics

Using Images

This is an image:

The next few pages provide the details you'll need to work with images. You'll learn how to load, display, and manipulate them.

Support for using images is spread across the java.applet, java.awt, and java.awt.image packages. Every image is represented by a java.awt.Image object. In addition to the Image class, the java.awt package provides other basic image support, such as the Graphics drawImage() methods, the Toolkit getImage() methods, and the MediaTracker class. In java.applet, the Applet getImage() methods make it easy for applets to load images using URLs. Finally, the java.awt.image package provides interfaces and classes that let you create, manipulate, and observe images.

Loading Images

The AWT makes it easy to load images in either of two formats: GIF and JPEG. The Applet and Toolkit classes provide getImage() methods that work for either format. You use them like this:
myImage = getImage(URL); //in a method in an Applet subclass only
    or
myImage = Toolkit.getDefaultToolkit().getImage(filenameOrURL);
The getImage() methods return immediately, so that you don't have to wait for an image to be loaded before going on to perform other operations in your program. While this improves performance, some programs require more control or information about image loading. You can track image loading status either by using the MediaTracker class or by implementing the imageUpdate() method, which is defined by the ImageObserver interface.

This section will also tell you how to create images on the fly by using the MemoryImageSource class.

Displaying Images

It's easy to display an image using the Graphics object that's passed into your update() or paint() method. You simply invoke a drawImage() method on the Graphics object. For example:
g.drawImage(myImage, 0, 0, this);
This section explains the four forms of drawImage(), two of which scale the image. Like getImage(), drawImage() is asynchronous, returning immediately even if the image hasn't been fully loaded or drawn yet.

Manipulating Images

This section gives you an overview of how to change images, using filters. (Scaling images is covered in Displaying Images.)


Previous | Next | Trail Map | Creating a User Interface | Working with Graphics