The “javax.imageio” package is used to deal with the Java image stuff. Here’s two “ImageIO” code snippet to read an image file.

1. Read from local file


File sourceimage = new File("c:\\mypic.jpg");
Image image = ImageIO.read(sourceimage);

2. Read from URL


URL url = new URL("http://www.mkyong.com/image/mypic.jpg");
Image image = ImageIO.read(url);

ImageIO Example

In this example, you will use ImageIO to read a file from an URL and display it in a frame.


package com.mkyong.image;

import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ReadImage 
{	
    public static void main( String[] args )
    {
    	Image image = null;
        try {
            URL url = new URL("http://www.mkyong.com/image/mypic.jpg");
            image = ImageIO.read(url);
        } catch (IOException e) {
        	e.printStackTrace();
        }
        
        JFrame frame = new JFrame();
        frame.setSize(300, 300);
        JLabel label = new JLabel(new ImageIcon(image));
        frame.add(label);
        frame.setVisible(true);
    }
}

Output…

read-image-from-url