By Alvin Alexander. Last updated: March 10, 2018
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.