Scaling Images

You may ask why the scale factor is calculated in the paint() method rather than the init() method. Some time could be saved by not recalculating the image's height and width every time the image is painted. After all the image size should be constant.

In this application the size of the image doesn't change, and indeed it will be a rare Image that changes size in the middle of an applet. However in the init() method the Image probably hasn't fully loaded. If instead you were to try the program below, which does exactly that, you'd see that the image wasn't scaled at all. The reason is that in this version the image hasn't loaded when you make the calls to getWidth() and getHeight() so they both return -1.

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

public class MagnifyImage extends Applet {

  private Image theImage;
  private int   scaledWidth;
  private int   scaledHeight;

  public void init() {
    String filename = this.getParameter("imagefile");
    theImage        = this.getImage(this.getDocumentBase(), filename);
    int scalefactor = Integer.parseInt(this.getParameter("scalefactor"));
    int width       = theImage.getWidth(this);
    int height      = theImage.getHeight(this);
    scaledWidth     =  width  * scalefactor;
    scaledHeight    =  height * scalefactor;

  public void paint (Graphics g) {

    g.drawImage(theImage, 0, 0, scaledWidth, scaledHeight, this);



Previous | Next | Top | Cafe au Lait

Copyright 1997-1999, 2002 Elliotte Rusty Harold
Last Modified February 13, 2002