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 ...
Get Killer Game Programming in Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.