Reading an Image from a File, InputStream, or URL - Java Network

Java examples for Network:URL

Description

Reading an Image from a File, InputStream, or URL

Demo Code

import java.awt.BorderLayout;
import java.awt.Image;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
  public static void main(String[] args) throws Exception {
    Image image = null;//from  w  w w  . ja  va  2  s.c  o  m
    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);
  }
}

Related Tutorials