        // View an image in a canvas. Adjust the dimensions of the canvas
        // to match the size of the image.
        // This is similar to the ImageViewer class which extends Frame
        // rather than Canvas.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;

class ImageCanvas extends Canvas {
    ImageCanvas(Image image){
        setImage(image);
        setup();
    }

        // Obtain the image from the producer.
    ImageCanvas(ImageProducer producer){
        setImage(createImage(producer));
        setup();
    }

        // Perform common frame setup for the two constructors.
    protected void setup(){
        // Dimensions are adjusted once the dimensions of
        // the image are known.
        final int initialWidth = 200, initialHeight = 200;
        setSize(initialWidth,initialHeight);
        setVisible(true);
    }

    public void paint(Graphics g){
        g.drawImage(getImage(),0,0,this);
    }

    // Override Component.imageUpdate - the implemention of ImageObserver.
    public boolean imageUpdate(Image img,int infoflags,int x, int y,
                                int width, int height){
        boolean result = super.imageUpdate(img,infoflags,x,y,width,height);
        // See if the image is complete.
        if((infoflags & ImageObserver.ALLBITS) != 0){
            // Set the canvas's dimensions.
            setSize(width,height);
        }
        else if((infoflags & (ImageObserver.ABORT | ImageObserver.ERROR)) != 0){
            System.err.println("Image error.");
        }
        else{
            // Ignore.
        }
        return result;
    }

    protected Image getImage(){
        return image;
    }

    protected void setImage(Image i){
        image = i;
    }    

    private Image image;
}
