Working with Graphics |
This is an image:The next few pages provide the details you'll need to work with images. You'll learn how to load, display, and manipulate them.
Support for using images is spread across the java.applet, java.awt, and java.awt.image packages. Every image is represented by a java.awt.Image object. In addition to the Image class, the java.awt package provides other basic image support, such as the Graphics
drawImage()
methods, the ToolkitgetImage()
methods, and the MediaTracker class. In java.applet, the Applet class provides an easy way for applets to load images using URLs. Finally, the java.awt.image package provides interfaces and classes that let you create, manipulate, and observe images.Loading Images
The AWT makes it easy to load images in either of two formats: GIF and JPEG. The Applet and Toolkit classes providegetImage()
methods that work for either format. You use them like this:ThemyImage = getImage(URL); //in an Applet subclass only or myImage = Toolkit.getDefaultToolkit().getImage(filenameOrURL);getImage()
methods return immediately, so that you don't have to wait for an image to be loaded before going on to perform other operations in your program. While this improves performance, some programs require more control or information about image loading. You can track image loading status either by using the MediaTracker class or by implementing theimageUpdate()
method defined by the ImageObserver interface.This section will also tell you how to add support for new image types and create images on the fly by using the MemoryImageSource class.
Displaying Images
It's easy to display an image using the Graphics object that's passed into yourupdate()
orpaint()
method. You simply invoke adrawImage()
method on the Graphics object. For example:This section explains the four forms ofg.drawImage(myImage, 0, 0, this);drawImage()
, two of which scale the image. LikegetImage()
,drawImage()
is asynchronous, returning immediately even if the image hasn't been fully loaded [or drawn?] yet.Manipulating Images
This section gives you an overview of how to change images, using filters. (Scaling images is covered in Displaying Images.)
Working with Graphics |