O'Reilly logo

Killer Game Programming in Java by Andrew Davison

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Buffering an Image

The BufferedImage class is a subclass of Image, so it can be employed instead of Image in methods such as drawImage(). BufferedImage has two main advantages: the data required for image manipulation are easily accessible through its methods, and BufferedImage objects are automatically converted to managed images by the JVM (when possible). A managed image may allow hardware acceleration to be employed when the image is being rendered.

The code in Example 5-2 is the ShowImage applet, recoded to use a BufferedImage.

Example 5-2. ShowImage applet (Version 2) using BufferedImage

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.ImageIO;


public class ShowImage extends JApplet
{
  private BufferedImage im;

  public void init()
  { try {
      im =ImageIO.read( getClass().getResource("ball.gif") );
    }
    catch(IOException e) {
      System.out.println("Load Image error:");
    }
  } // end of init()

  public void paint(Graphics g)
  {  g.drawImage(im, 0, 0, this);  }
}

The simplest, and perhaps fastest, way of loading a BufferedImage object is with read() from the ImageIO class. Some tests suggest that it may be 10 percent faster than using ImageIcon, which can be significant when the image is large. InputStream, and ImageInputStream are different versions of read() for reading from a URL.

Optimizing the BufferedImage is possible so it has the same internal data format and color model as the underlying graphics device. This requires us to make a copy ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required