![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e694. Reading an Image from a File, InputStream, or URLThis example demonstrates how to use thejavax.imageio package to
read an image from a file, input stream, or URL. The example also
demonstrates how to display the image on the screen.
GIF, PNG, and JPEG formats are supported by the
This example works only in J2SE 1.4. For a method that works since J2SE 1.3, see e594 Reading an Image or Icon from a File. Image image = null; try { // Read from a file File file = new File("image.gif"); image = ImageIO.read(file); // Read from an input stream InputStream is = new BufferedInputStream( new FileInputStream("image.gif")); image = ImageIO.read(is); // Read from a URL URL url = new URL("http://hostname.com/image.gif"); image = ImageIO.read(url); } catch (IOException e) { } // Use a label to display the image JFrame frame = new JFrame(); JLabel label = new JLabel(new ImageIcon(image)); frame.getContentPane().add(label, BorderLayout.CENTER); frame.pack(); frame.setVisible(true);
e696. Listing the Image Formats That Can Be Read and Written e697. Determining If an Image Format Can Be Read or Written e698. Determining the Format of an Image in a File e699. Compressing a JPEG File © 2002 Addison-Wesley. |