Determining the Size of an Image

If the rectangle you draw an image in is not proportional to the size of the image drawn, then the image may appear squashed or distorted.

To avoid disproportionate scaling you can use the Image's getHeight(ImageObserver observer) and getWidth(ImageObserver observer) 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);
light bulb This applet reads an image file in the same directory as the HTML file and displays it at a specified magnification. The name of the image file and the magnification factor are specified via PARAMs. For example here's an applet tag that displays the image at half size:

This image was loaded with this <APPLET> tag:

<applet code="MagnifyImage" width=80 height=95>
<PARAM name=imagefile value=lightbulb.gif>
<img src=lightbulb.gif width=80 height=95>
import java.awt.*;
import java.applet.Applet;

public class MagnifyImage extends Applet {

  private Image picture;
  private double scalefactor;

  public void init() {
    String filename=this.getParameter("imagefile");
    if (filename != null) {
      this.picture = this.getImage(getDocumentBase(), filename);
    try {
      scalefactor = Double.valueOf(
    catch (Exception e) {
      this.scalefactor = 1.0;  
  public void paint (Graphics g) {
    if (this.picture != null) {
      int width = picture.getWidth(this);
      int height = picture.getHeight(this);
      int scaleWidth = (int) (width * scalefactor);
      int scaleHeight = (int) (height * scalefactor);
      g.drawImage(picture, 0, 0, scaleWidth, scaleHeight, this);
    else {
      g.drawString("Missing imagefile PARAM element in HTML page", 10, 10);        


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998 Elliotte Rusty Harold
Last Modified April 10, 2000