Image Loading
Contents:
How Images are Loaded
Brief Tour of sun.awt.image
How Images are Loaded
You have seen how easy it is to display an image on screen and have probably guessed that there's more going on behind the scenes. The getImage()
and drawImage()
methods trigger a series of events that result in the image being available for display on the ImageObserver
. The image is fetched asynchronously in another thread. The entire process[1] goes as follows:
[1] This summary covers Sun's implementation ( JDK). Implementations that don't derive from the JDK may behave completely differently.
- The call to
getImage()
triggersToolkit
to callcreateImage()
for the image'sInputStreamImageSource
(which is aURLImageSource
in this case; it would be aFileImageSource
if we were loading the image from a local file). - The
Toolkit
registers the image as being "desired." Desired just means that something will eventually want the image loaded. The system then waits until anImageObserver
registers its interest in the image. - The
drawImage()
method (use ofMediaTracker
orprepareImage()
) registers anImageObserver
as interested. - Registering an
ImageObserver
kicks the image'sImageRepresentation
into action; this is the start of the loading process, although image data isn't actually transferred until step 9.ImageRepresentation
implements theImageConsumer
interface. - The start of production registers the image source (
ImageProducer
URLImageSource
) with theImageFetcher
and also registers theImageRepresentation
as anImageConsumer
for the image. - The
ImageFetcher
creates a thread to get the image from its source. - The
ImageFetcher
reads data and passes it along to theInputStreamImageSource
, which is aURLImageSource
. - The
URLImageSource
determines thatJPEGImageDecoder
is the properImageDecoder
for converting the input stream into anImage
. (OtherImageDecoders
are used for other image types, like GIF.) - The
ImageProducer
starts reading the image data from the source; it calls theImageConsumer
(i.e., theImageRepresentation
) as it processes the image. The most important method in theImageConsumer
interface issetPixels()
, which delivers pixel data to the consumer for rendering onscreen. - As the
ImageConsumer
(i.e., theImageRepresentation
) gets additional information, it notifies theImageObserver
viaimageUpdate()
calls. - When the image is fully acquired across the network, the thread started by the
ImageFetcher
stops.
As you see, there are a lot of unfamiliar moving pieces. Many of them are from the java.awt.image
package and are discussed in Image Processing. Others are from the sun.awt.image
package; they are hidden in that you don't need to know anything about them to do image processing in Java. However, if you're curious, we'll briefly summarize these classes in the next section.