Scaling Images
Java expert Geoff Friesen shows how to perform image scaling by using one of the drawImage methods in the Abstract Windowing Toolkit's Graphics class.
Download a zip containing the source files for this article.
Several drawImage methods can be called to perform scaling prior to drawing an image. To demonstrate how this works, Listing 1 presents source code to an ImageScale applet. This applet draws an original image along with a scaled-down version of the image.
Listing 1 The ImageScale applet source code
7// ImageScale.java import java.awt.*; import java.applet.Applet; import java.awt.image.ImageObserver; public class ImageScale extends Applet { Image im; public void init () { im = getImage (getDocumentBase (), "twain.jpg"); } public void paint (Graphics g) { if (g.drawImage (im, 0, 0, this)) { int width = im.getWidth (this); int height = im.getHeight (this); g.drawImage (im, width, 0, width + width / 2, height / 2, 0, 0, width, height, this); } } }
ImageScale takes advantage of drawImage returning a Boolean true value after the original image is completely loaded. After it's loaded, the width and height of this image are obtained by calling Image's getWidth and getHeight methods. These methods take an ImageObserver argument—an object that implements the ImageObserver interface—and return -1 until the producer has produced the width/height information. Because they're not called until drawImage returns true, getWidth and getHeight are guaranteed to return the image's width and height. A second version of drawImage (with 10 arguments) is called to load and draw the scaled image.
Scaling is achieved by dividing the target image's lower-right corner coordinates by a specified value. ImageScale divides these coordinates by 2. Figure 1 shows the result.
ImageScale shows original and scaled-down images of Mark Twain (an early American author and humorist).
The Image class provides the getScaledInstance method for generating a prescaled version of an image. Instead of calling a drawImage method to scale and then draw, you can call getScaledInstance to prescale and then a drawImage method to only draw. This is useful in situations in which calling drawImage to scale and then draw results in a degraded appearance (because scaling takes time).
About the Author
Geoff Friesen is a co-author of Special Edition Using Java 2, Standard Edition (Que, 2001, ISBN 0-7897-2468-5). His contribution consists of nine chapters that explore the Java Foundation Classes and the Java Media Framework. Geoff also writes the monthly Java 101 column for JavaWorld and is the former moderator of ITworld.com's Java Beginner discussion forum.