Monday, December 21, 2009

Reading an Image from a file, inputStream, or URL

This Java tip illustrates a method of reading an Image from a file, inputStream, or URL. This tip also includes displaying of an image on the screen. Further, javax.imageio package is used to read an image from a file. This example works only above J2SE 1.4.


Image image = null;
try {
File sourceimage = new File("source.gif");
image = ImageIO.read(sourceimage);

InputStream is = new BufferedInputStream(
new FileInputStream("source.gif"));
image = ImageIO.read(is);

URL url = new URL("http://java-tips.org/source.gif");
image = ImageIO.read(url);
} catch (IOException e) {
}

JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);

Ref: java-tips.org

No comments:

Computers Add to Technorati Favorites Programming Blogs - BlogCatalog Blog Directory