Doing More with Images

   


You have already seen how to build up simple images by drawing lines and shapes. Complex images, such as photographs, are usually generated externally, for example, with a scanner or special image-manipulation software. (As you will see in Volume 2, it is 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 them into a Java application and display them on Graphics objects. As of JDK 1.4, reading an image is very simple. If the image is stored in a local file, call

 String filename = "..."; Image image = ImageIO.read(new File(filename)); 

Otherwise, you can supply a URL:

 String urlname = "..."; Image image = ImageIO.read(new URL(urlname)); 

The read method throws an IOException if the image is not available. We discuss the general topic of exception handling in Chapter 11. 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 drawImage method of the Graphics class.

 public void paintComponent(Graphics g) {    . . .    g.drawImage(image, x, y, null); } 

Example 7-7 takes this a little bit further and tiles the window with the graphics image. The result looks like the screen shown in Figure 7-15. We do the tiling in the paintComponent method. We first draw one copy of the image in the top-left corner and then use the copyArea call to copy it into the entire window:

 for (int i = 0; i * imageWidth <= getWidth(); i++)   for (int j = 0; j * imageHeight <= getHeight(); j++)       if (i + j > 0)          g.copyArea(0, 0, imageWidth, imageHeight, i * imageWidth, j * imageHeight); 

Figure 7-15. Window with tiled graphics image


NOTE

To load an image with JDK 1.3 or earlier, you should use the MediaTracker class instead. A media tracker can track the acquisition of one or more images. (The name "media" suggests that the class should also be able to track audio files or other media. While such an extension may have been envisioned for the future, the current implementation tracks images only.)

You add an image to a tracker object with the following command:

 MediaTracker tracker = new MediaTracker(component); Image img = Toolkit.getDefaultToolkit().getImage(name); int id = 1; // the ID used to track the image loading process tracker.addImage(img, id); 

You can add as many images as you like to a single media tracker. Each of the images should have a different ID number, but you can choose any numbering that is convenient. To wait for an image to be loaded completely, you use code like this:

 try { tracker.waitForID(id); } catch (InterruptedException e) {} 

If you want to acquire multiple images, then you can add them all to the media tracker object and wait until they are all loaded. You can achieve this with the following code:

 try { tracker.waitForAll(); } catch (InterruptedException e) {} 


Example 7-7 shows the full source code of the image display program. This concludes our introduction to Java graphics programming. For more advanced techniques, you can turn to the discussion about 2D graphics and image manipulation in Volume 2.

Example 7-7. ImageTest.java
  1. import java.awt.*;  2. import java.awt.event.*;  3. import java.io.*;  4. import javax.imageio.*;  5. import javax.swing.*;  6.  7. public class ImageTest  8. {  9.    public static void main(String[] args) 10.    { 11.       ImageFrame frame = new ImageFrame(); 12.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 13.       frame.setVisible(true); 14.    } 15. } 16. 17. /** 18.     A frame with an image panel 19. */ 20. class ImageFrame extends JFrame 21. { 22.    public ImageFrame() 23.   { 24.       setTitle("ImageTest"); 25.       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 26. 27.       // add panel to frame 28. 29.       ImagePanel panel = new ImagePanel(); 30.       add(panel); 31.    } 32. 33.    public static final int DEFAULT_WIDTH = 300; 34.    public static final int DEFAULT_HEIGHT = 200; 35. } 36. 37. /** 38.    A panel that displays a tiled image 39. */ 40. class ImagePanel extends JPanel 41. { 42.    public ImagePanel() 43.    { 44.       // acquire the image 45.       try 46.       { 47.          image = ImageIO.read(new File("blue-ball.gif")); 48.       } 49.       catch (IOException e) 50.       { 51.          e.printStackTrace(); 52.       } 53.    } 54. 55.    public void paintComponent(Graphics g) 56.    { 57.       super.paintComponent(g); 58.       if (image == null) return; 59. 60.       int imageWidth = image.getWidth(this); 61.       int imageHeight = image.getHeight(this); 62. 63.       // draw the image in the upper-left corner 64. 65.       g.drawImage(image, 0, 0, null); 66.       // tile the image across the panel 67. 68.       for (int i = 0; i * imageWidth <= getWidth(); i++) 69.          for (int j = 0; j * imageHeight <= getHeight(); j++) 70.             if (i + j > 0) 71.                g.copyArea(0, 0, imageWidth, imageHeight, 72.                   i * imageWidth, j * imageHeight); 73.    } 74. 75.    private Image image; 76. } 


 javax.swing.ImageIO 1.4 

  • static BufferedImage read(File f)

  • static BufferedImage read(URL u)

    read an image from the given file or URL.


 java.awt.Image 1.0 

  • Graphics getGraphics()

    gets a graphics context to draw into this image buffer.

  • void flush()

    releases all resources held by this image object.


 java.awt.Graphics 1.0 

  • boolean drawImage(Image img, int x, int y, ImageObserver observer)

    draws an unscaled image. Note: This call may return before the image is drawn.

    Parameters:

    img

    The image to be drawn

     

    x

    The x-coordinate of the upper-left corner

     

    y

    The y-coordinate of the upper-left corner

     

    observer

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


  • boolean drawImage(Image img, int x, int y, int width, int height, 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.

    Parameters:

    img

    The image to be drawn

     

    x

    The x-coordinate of the upper-left corner

     

    y

    The y-coordinate of the upper-left corner

     

    width

    The desired width of image

     

    height

    The desired height of image

     

    observer

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


  • void copyArea(int x, int y, int width, int height, int dx, int dy)

    copies an area of the screen.

    Parameters:

    x

    The x-coordinate of the upper-left corner of the source area

     

    y

    The y-coordinate of the upper-left corner of the source area

     

    width

    The width of the source area

     

    height

    The height of the source area

     

    dx

    The horizontal distance from the source area to the target area

     

    dy

    The vertical distance from the source area to the target area


  • void dispose()

    disposes of this graphics context and releases operating system resources. You should always dispose of the graphics contexts that you receive from calls to methods such as Image.getGraphics, but not the ones handed to you by paintComponent.


 java.awt.Component 1.0 

  • Image createImage(int width, int height)

    creates an off-screen image buffer to be used for double buffering.

    Parameters:

    width

    The width of the image

     

    height

    The height of the image



 java.awt.MediaTracker 1.0 

  • MediaTracker(Component c)

    tracks images that are displayed in the given component.

  • void addImage(Image image, int id)

    adds an image to the list of images being tracked. When the image is added, the image loading process is started.

    Parameters:

    image

    The image to be tracked

     

    id

    The identifier used to later refer to this image


  • void waitForID(int id)

    waits until all images with the specified ID are loaded.

  • void waitForAll()

    waits until all images that are being tracked are loaded.


       
    top



    Core Java 2 Volume I - Fundamentals
    Core Java(TM) 2, Volume I--Fundamentals (7th Edition) (Core Series) (Core Series)
    ISBN: 0131482025
    EAN: 2147483647
    Year: 2003
    Pages: 132

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net