Displaying Images Core Java

You have already seen how to build up simple drawings by painting lines and shapes. Complex images, such as photographs, are usually generated externally, for example, with a scanner or special image-manipulation software. (itis also possible to produce an image, pixel by pixel, and store the result in an array. This procedure is common for fractal images, for example.)

Once images are stored in local files or someplace on the Internet, you can read theminto a Java application and display them on Graphics objects. As of Java SE 1.4, reading an image is very simple. If the image is stored in a local file, call

The read method throws an IOExceptionif the image is not available. For now, our sample program just catches that exception and prints a stack trace if it occurs.

Now the variable image contains a reference to an object that encapsulates the image data. You can display the image with the draw Image method of the Graphics class.

Listing below takes this a little bit further and tiles the window with the graphics image.

The result looks like the screen shown in Figure below. We do the tiling in the paintComponentmethod. We first draw one copy of the image in the top-left corner and then use thecopyAreacall to copy it into the entire window:

Window with tiled graphics image

Window with tiled graphics image

javax.imageio.ImageIO

  • staticBufferedImage read(File f)
  • staticBufferedImage read(URL u)
    reads an image from the given file or URL.

java.awt.Graphics

  • booleandrawImage(Image img, int x, int y, ImageObserver observer)
    draws an unscaled image. Note: This call may return before the image is drawn.
  • booleandrawImage(Image img, int x, int y, int width, intheight, ImageObserver observer) draws a scaled image. The system scales the image to fit into a region with the given width and height. Note: This call may return before the image is drawn.
  • void copyArea(int x, int y, int width, int height, int dx, intdy)

observerThe object to notify of the progress of the rendering process (may be null)

observerThe object to notify of the progress of the rendering process (may be null)

This concludes our introduction to Java graphics programming. For more advanced techniques, you can turn to the discussion about 2D graphics and image manipulation later. In the next section, you will learn how your programs react to user input.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Topics