The first version returns anImageobject that encapsulates the image found at the location
specified byurl.The second version returns anImageobject that encapsulates the image
found at the location specified byurland having the name specified byimageName.
Displaying an Image
Once you have an image, you can display it by usingdrawImage( ), which is a member of
theGraphicsclass. It has several forms. The one we will be using is shown here:
boolean drawImage(ImageimgObj, intleft, inttop, ImageObserverimgOb)
This displays the image passed inimgObjwith its upper-left corner specified byleftandtop.
imgObis a reference to a class that implements theImageObserverinterface. This interface
is implemented by all AWT components. Animage observeris an object that can monitor an
image while it loads.ImageObserveris described in the next section.
WithgetImage( )anddrawImage( ), it is actually quite easy to load and display an
image. Here is a sample applet that loads and displays a single image. The fileseattle.jpgis
loaded, but you can substitute any GIF, JPG, or PNG file you like (just make sure it is
available in the same directory with the HTML file that contains the applet).
/*
*/
import java.awt.*;
import java.applet.*;
public class SimpleImageLoad extends Applet
{
Image img;
public void init() {
img = getImage(getDocumentBase(), getParameter("img"));
}
public void paint(Graphics g) {
g.drawImage(img, 0, 0, this);
}
}
In theinit( )method, theimgvariable is assigned to the image returned by
getImage( ). ThegetImage( )method uses the string returned bygetParameter(“img”)
as the filename for the image. This image is loaded from aURLthat is relative to the
result ofgetDocumentBase( ), which is theURLof the HTML page this applet tag was in.
The filename returned bygetParameter(“img”)comes from the applet tag
“img” value=“seattle.jpg”>. This is the equivalent, if a little slower, of using the HTML
tag. Figure 25-1 shows what it looks like
when you run the program.
Chapter 25: Images 757