How to read an image from file or URL

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
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Mayaa

    Nice one Yong!! Check out this tutorial http://www.compiletimeerror.com/2013/08/java-downloadextract-all-images-from.html to download all the images from a website URL.. May help..

  • Max

    Mkyong, I’m making an application that’s requiring you to pretty much press a JButton to load information from a JSon page and needless to say I need it to load an image too.. I can’t figure out the button code.. Could you please help me?

  • Jarvis Prestidge

    Great tutorial, really clear and to the point. Keep it up :D

  • Jimmy

    I tested your code, and I keep getting javax.imageio.IIOException: Can’t get input stream from URL! error

  • http://[email protected] ramesh

    hi sir, iam ramesh thank u very much given this code i am doing project on visual cryptography i want to do the overlap with another share so for that one what i have to do
    File sourceimage = new File(“commonshare.png”); this image is visible now we browse the another image and it is overlap with the common share.
    what should i do sir plz help me plz help me sir

  • Jerry

    I am getting error in the line
    ” Image image = ImageIO.read(sourceimage); ”
    saying
    ” Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor ” what is the solution for this.

    • http://www.mkyong.com mkyong

      Cant simulate it, please post your full source code