img
images. These images, when properly created, can be of much higher fidelity as well as more
highly compressed than a GIF encoding of the same source image. Another file format is
PNG. It too is an alternative to GIF. In almost all cases, you will never care or notice which
format is being used in your programs. The Java image classes abstract the differences
behind a clean interface.
Image Fundamentals: Creating, Loading, and Displaying
There are three common operations that occur when you work with images: creating an
image, loading an image, and displaying an image. In Java, the Image class is used to refer
to images in memory and to images that must be loaded from external sources. Thus, Java
provides ways for you to create a new image object and ways to load one. It also provides
a means by which an image can be displayed. Let's look at each.
Creating an Image Object
You might expect that you create a memory image using something like the following:
Image test = new Image(200, 100); // Error -- won't work
Not so. Because images must eventually be painted on a window to be seen, the Image class
doesn't have enough information about its environment to create the proper data format for the
screen. Therefore, the Component class in java.awt has a factory method called createImage( )
that is used to create Image objects. (Remember that all of the AWT components are subclasses
of Component, so all support this method.)
The createImage( ) method has the following two forms:
Image createImage(ImageProducer imgProd)
Image createImage(int width, int height)
The first form returns an image produced by imgProd, which is an object of a class that
implements the ImageProducer interface. (We will look at image producers later.) The
second form returns a blank (that is, empty) image that has the specified width and height.
Here is an example:
Canvas c = new Canvas();
Image test = c.createImage(200, 100);
This creates an instance of Canvas and then calls the createImage( ) method to actually make
an Image object. At this point, the image is blank. Later you will see how to write data to it.
Loading an Image
The other way to obtain an image is to load one. One way to do this is to use the getImage( )
method defined by the Applet class. It has the following forms:
Image getImage(URL url)
Image getImage(URL url, String imageName)
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home