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 =;

2. Read from URL

URL url = new URL("");
Image image =;

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 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("");
            image =;
        } catch (IOException e) {
        JFrame frame = new JFrame();
        frame.setSize(300, 300);
        JLabel label = new JLabel(new ImageIcon(image));


Tags :

About the Author

Founder of and, 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.


  • Mayaa

    Nice one Yong!! Check out this tutorial 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 =; ”
    ” Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor ” what is the solution for this.

    • mkyong

      Cant simulate it, please post your full source code