Use the Java ImageIO class to read an image file

Wow, I haven't worked with images with Java in a little while, and it turns out that opening and reading an image file 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 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.

Thanks

Thanks

Post new comment

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