Reading an Image from a File, InputStream, or URL

This example demonstrates how to use the javax.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 javax.imageio package by default.

This example works only in J2SE 1.4. For a method that works since J2SE 1.3, see 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);

Comments

5 Mar 2010 - 12:59am by Anonymous

thanx a lot it really helped me

24 Mar 2010 - 5:27am by Anonymous (not verified)

thanx... would you by any chance help me to make the image resize according to the size of the frame?

12 Jul 2010 - 7:57am by Anonymous (not verified)

new FileInputStream("image.gif")); results in FileNotFound exception. Help?

26 Jul 2010 - 2:35pm by Art (not verified)

To the poster on Jul 12, image.gif needs to be located in your root directory. Otherwise just specify path to the image: new FileInputStream("/images/navigation/back.gif")); or whatever the path is relative to your root directory.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.