Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Working with Graphics

Loading Images

This page describes how to get the Image object corresponding to an image. As long as the image data is in GIF or JPEG format and you know its filename or URL, it's easy to get an Image object for it: just use one of the Applet or Toolkit getImage() methods. The getImage() methods return immediately, without checking whether the image data exists. The actual loading of image data normally doesn't start until the first time the program tries to draw the image.

For many programs, this invisible background loading works well. Others, though, need to keep track of the progress of the image loading. This page explains how to do so using the MediaTracker class and the ImageObserver interface.

Finally, this page tells you how to create images on the fly, using a class such as MemoryImageSource.

Using the getImage() Methods

This section discusses first the Applet getImage() methods and then the Toolkit getImage() methods.

The Applet class supplies two getImage() methods:

Only applets can use the Applet getImage() methods. Moreover, the Applet getImage() methods don't work until the applet has a full context (AppletContext). For this reason, these methods do not work if called in a constructor or in a statement that declares an instance variable. You should instead call getImage() from a method such as init().

This following code examples show you how to use the Applet getImage() methods. See Creating a GUI(in the Writing Applets trail) for an explanation of the getCodeBase() and getDocumentBase() methods.

//In a method in an Applet subclass:
Image image1 = getImage(getCodeBase(), "imageFile.gif");
Image image2 = getImage(getDocumentBase(), "anImageFile.jpeg");
Image image3 = getImage(new URL("http://java.sun.com/graphics/people.gif"));

The Toolkit class declares two more getImage() methods:

You can get a Toolkit object either by invoking Toolkit's getDefaultToolkit() class method or by invoking the Component getToolkit() instance method. The Component getToolkit() method returns the toolkit that was used (or will be used) to implement the Component.

Here are examples of using the Toolkit getImage() methods. Every Java application and applet can use these methods, with applets subject to the usual security restrictions. You can read about applet security in Security Restrictions(in the Writing Applets trail).

Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image1 = toolkit.getImage("imageFile.gif");
Image image2 = toolkit.getImage(new URL("http://java.sun.com/graphics/people.gif"));

Requesting and Tracking Image Loading: MediaTracker and ImageObserver

The AWT provides two ways for you to track image loading: the MediaTracker(in the API reference documentation) class and the ImageObserver(in the API reference documentation) interface. The MediaTracker class is sufficient for many programs. You just create a MediaTracker instance, tell it to track one or more images, and then ask the MediaTracker the status of those images, as needed. An example is explained in Improving the Appearance and Performance of Image Animation.

The animation example shows two particularly useful MediaTracker features: requesting that the data for a group of images be loaded, and waiting for a group of images to be loaded. To request that the image data for a group of images be loaded, you can use the forms of checkID() and checkAll() that take a boolean argument. Setting the boolean argument to true starts loading the data for any images that aren't yet being loaded. Or you can request that the image data be loaded and wait for it using the waitForID() and waitForAll() methods.

The ImageObserver interface lets you keep even closer track of image loading than MediaTracker allows. The Component class uses it so that components are repainted as the images they display are loaded. To use the ImageObserver interface, you implement the ImageObserver imageUpdate() method and make sure the implementing object is registered as the image observer. Usually, this registration happens when you specify an ImageObserver to the drawImage method, as described on the next page. The imageUpdate() method is called whenever information about an image becomes available.

Here is an example of implementing the Image Observer interface's imageUpdate() method. This example uses imageUpdate() to position two images as soon as their size is known, and to repaint every 100 milliseconds until both images are loaded. (Here's the whole program.)

public boolean imageUpdate(Image theimg, int infoflags,
                           int x, int y, int w, int h) {
    if ((infoflags & (ERROR)) != 0) {
        errored = true;
    }
    if ((infoflags & (WIDTH | HEIGHT)) != 0) {
        positionImages();
    }
    boolean done = ((infoflags & (ERROR | FRAMEBITS | ALLBITS)) != 0);
    // Repaint immediately if we are done, otherwise batch up
    // repaint requests every 100 milliseconds
    repaint(done ? 0 : 100); 
    return !done; //If done, no further updates required.
}

If you browse the MediaTracker API documentation, you might notice that the Component class defines two useful-looking methods: checkImage() and prepareImage(). The MediaTracker class has made these methods largely unnecessary.

Creating Images with MemoryImageSource

With the help of an image producer such as the MemoryImageSource(in the API reference documentation) class, you can construct images from scratch. The following code example calculates a 100x100 image representing a fade from black to blue along the X axis and a fade from black to red along the Y axis.
int w = 100;
int h = 100;
int[] pix = new int[w * h];
int index = 0;
for (int y = 0; y < h; y++) {
    int red = (y * 255) / (h - 1);
    for (int x = 0; x < w; x++) {
          int blue = (x * 255) / (w - 1);
          pix[index++] = (255 << 24) | (red << 16) | blue;
    }
}
Image img = createImage(new MemoryImageSource(w, h, pix, 0, w));


Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Working with Graphics