In this post, I will show you how to read and write image files in Java. I will demonstrate 2 different ways of doing this. The first is with the ImageIO class, and the second is with the JDeli image library. Both provide encoding and decoding of images. JDeli can read and write a very wide range of image formats. Here is the full list on Image file conversions supported.
How to read images in Java
Reading images in Java involves converting external image formats (e.g. JPEG, PNG etc) into an internal format (i.e. BufferedImage) that can be used by a Java program.
One way to read an image in Java is to use ImageIO. For example, the following code could be used to read a PNG file:
File imageFile = new File("path\\to\\image\\example-png.png");
BufferedImage image = ImageIO.read(imageFile);
To see which image types can be read with ImageIO, the getReaderFormatNames() method will return an array of Strings containing the file types that can be understood by the current set of registered readers.
An alternative to ImageIO is JDeli, our Java Image Library. JDeli can easily be swapped in to replace ImageIO, as it also has static read and write methods. The only change you would need to make in the above code would be to change the ImageIO class to JDeli:
BufferedImage image = JDeli.read(imageFile);
All file types that can be read by JDeli can be found in our documentation.
How to write images in Java
Writing an image in Java involves converting an internal image format (BufferedImage) to an external format (e.g. JPEG, PNG etc).
If I wanted to write the BufferedImage I created in the previous example to a Tiff file, I could do the following using ImageIO:
File outputFile = new File("path\\to\\image\\example-tiff.tiff");
ImageIO.write(image, "TIFF", outputFile);
To see which image types ImageIO write out, the getWriterFormatNames() method will return an array of Strings containing the file types that can understood by the current set of registered writers.
Or with JDeli:
JDeli.write(image, JDeli.OutputFormat.TIFF, outputFile);
ImageIO or JDeli?
ImageIO is the only supported solution that Java provides for reading and writing images as part of the JDK and it is free. However, it has several issues and has not seen much improvement in any recent releases. We decided to stop using it in our own commercial code some time ago. Instead, we developed our own improved Java image library, JDeli.
Why use JDeli?
JDeli offers a range of advantages over ImageIO and alternatives, including:
- prevents heap related JVM crashes
- implements unsupported image formats
- reduce output file size
- improve read/write performance
- supports threading
- superior image scaling algorithms
Watch a video tutorial on how to convert images in Java with ImageIO or JDeli.
if you would like to see how to read and write images in Java with ImageIO or JDeli, we also have a video on youtube.