Resizing Images

You're not restricted to drawing an image at its natural width and height. The following variation on the paint() method let's you specify the width and height with which the image will be drawn:

public boolean drawImage(Image img, int x, int y, 
int width, int height, ImageObserver io) 
Here width and height are the width and height at which the image will be drawn in pixels. All other arguments are the same as before.

This image was loaded with this <APPLET> tag:

<applet code="FillWithImage" width=100 height=200>
<PARAM name=imagefile value=lightbulb.gif>
<img src=lightbulb.gif width=100 height=200>
</applet>
Here's the code that produced it:

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


public class FillWithImage extends Applet {

  private Image picture;

  public void init() {
  
    String filename = this.getParameter("imagefile");
    if (filename != null) {
      this.picture = this.getImage(this.getDocumentBase(), filename);
    }
    
  }
  
  public void paint (Graphics g) {
  
    if (this.picture != null) {
      g.drawImage(this.picture, 0, 0, 
       this.getSize().height, this.getSize().width, this);
    }
    else {
      g.drawString("Missing imagefile PARAM element in HTML page", 10, 10);    
    }
    
  }

}

Previous | Next | Top
Last Modified April 10, 1999
Copyright 1997-1999 Elliotte Rusty Harold
elharo@metalab.unc.edu