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

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.