Scaling Images

You can scale an image into a particular rectangle using this version of the drawImage() method:

public boolean drawImage(Image img, int x, int y, int width, 
 int height, ImageObserver io) 

width and height specify the size of the rectangle to scale the image into. All other arguments are the same as before. If the scale is not in proportion to the size of the image, it can end up looking quite squashed.

To avoid disproportionate scaling use the image's getHeight() and getWidth() methods to determine the actual size. Then scale appropriately. For instance this is how you would draw an Image scaled by one quarter in each dimension:

g.drawImage(img, 0, 0, img.getWidth(this)/4, img.getHeight(this)/4, this);

This program reads a GIF file in the same directory as the HTML file and displays it at a specified magnification. The name of the GIF file and the magnification factor are specified via PARAMs.

import java.awt.*;
import java.applet.*;

public class MagnifyImage extends Applet {

  private Image image;
  private int   scaleFactor;

  public void init() {
    String filename   = this.getParameter("imagefile");
    this.image       = this.getImage(this.getDocumentBase(), filename);
    this.scaleFactor = Integer.parseInt(this.getParameter("scalefactor")); 
  }
  
  public void paint (Graphics g) {
    int width    = this.image.getWidth(this);
    int height   = this.image.getHeight(this);
    scaledWidth  = width * this.scaleFactor;
    scaledHeight = height * this.scaleFactor;
    g.drawImage(this.image, 0, 0, scaledWidth, scaledHeight, this);
  }

}

This applet is straightforward. The init() method reads two PARAMs, one the name of the image file, the other the magnification factor. The paint() method calculates the scale and then draws the image.


Previous | Next | Top | Cafe au Lait

Copyright 1997-1999 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified October 21, 1999