Use the Java ImageIO class to read an image file

Wow, I haven't worked with images in Java in a while, and it turns out that opening and reading an image file in Java is very easy these days. Just use the read method of the Java ImageIO class, and you can open/read images in a variety of formats (GIF, JPG, PNG) in basically one line of Java code.

Here’s a sample Java class that demonstrates how to read an image file. As you’ll see from the example, you open and read the file in one line of code, and everything else is boilerplate:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class JavaImageIOTest
{

  public JavaImageIOTest()
  {
    try
    {
      // the line that reads the image file
      BufferedImage image = ImageIO.read(new File("/Users/al/some-picture.jpg"));
      // work with the image here ...
    } 
    catch (IOException e)
    {
      // log the exception
      // re-throw if desired
    }
  }

  public static void main(String[] args)
  {
    new ImageIOTest();
  }

}

As you can see from this sample Java code, the ImageIO class read method can throw an IOException, so you need to deal with that. I’ve dealt with it using a try/catch block, but you can also just throw the exception.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.