Loading an Image
The other way to obtain an image is to load one. To do this, use the getlmage( ) method defined by the Applet class. It has the following forms:

Image getimage(URL 111:1)
Image getimage Ikl, url, String image Name)

The first version returns an Image object that encapsulates the image found at
the location specified by url. The second version returns an Image object that
encapsulates the image found at the location specified by url and having the nam~
specified by image Name.

Displaying an Image
Once you have an image, you can display it by using drawImage(), which is a member of the Graphics class. It has several forms. The one we will be using is shown here boolean drawlmageflmage imgObj, int ieff, int to!" Image Observer image) " ' This displays the image passed in imgObj with its upper-left comer specified by lep and top. imgOb is a reference to a class that implements the ImageObserver interface. This
interface is implemented by all AWT components. An image observer is an object that .can Monitor an image while it loads, Image

Observer is .described in the next section.
With getImage( ) and draw image (),,it is actually quite easy fo load and display an image. Here is a sample' applet that loads and displays a single image. The file seattle.jpg is loaded, but you can substitute any GIF or JPG file you like Gust make sure it is available in the same directory with the HtML file that contains the applet ( ) .

In the init( ) method; the img variable is assigned to the image returned by getlmage ( ). The getimage ( ) method uses the string returned by getParameter(image) as the filename for the image. This image is loaded from a URL that is relative to the result of getDocumentBase(), which is the URL of the HTML page this applet tag was in. The filename returned by getimage rameter("img") comes from the applet tag -param

name="img" valuee=seattle.jpg">.

This is the equivalent, if a little slower, of using the
HTML tag <img src=lfs~!attle.jpg" width=>248 height=1~6>.

looks like when you run the program. When this applet ruts it starts loading image in the init() method. Onscreen you can see the image as it loads from the network, because Apple's implementation of thc ImageObserver interface calls paint( ) every time more image data arrives,
Seeing the image load is somewhat informative, but it might be better if you use the time it takes to load the image to do other things in parallel. That way, the fully formed image can simply appear on the screen in an instant, once it is fully loaded. You can use ImageObserver, de-scribed' next, to monitor loading an image while you paint the screen with other information.

Share This