O'Reilly logo

Java 2D Graphics by Jonathan Knudsen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.2. Where Do Images Come From?

You can either load an image from an input stream or create a fresh image.

9.2.1. Loading Images

The JDK knows how to create images from GIF and JPEG data. There are four methods that load these types of images from URLs or files. Note that these methods do, in fact, return Images and not BufferedImages. If you want to create writable versions of these Images, you'll have to convert the Image to a BufferedImage first. I'll describe how to do that later in this chapter.

9.2.1.1. In applets

Applets can load images from URLs using two methods in the java.applet.Applet class.

public Image getImage(URL url)

This method returns an Image that represents image data located at the supplied URL. This method returns immediately. The image data is not loaded until you try to display the image. Interestingly, this method does not throw any exceptions, because the data loading is not performed when the Image is created.

public Image getImage(URL url, String name)

This is the same as the method above, except that the image data is located at the file name, relative to the given URL.

Let's say you have an image called oreilly.gif, located in the same place as the HTML page that contains your applet. You might, therefore, obtain an Image like this:

Image tarsier = getImage(getDocumentBase(), "oreilly.gif");

The following complete applet loads the image and displays it:

import java.applet.*; import java.awt.*; public class ShowImage extends Applet { private ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required