In this article I will show you how to read JPEG images in Java using ImageIO, JAI and JDeli.
We previously used ImageIO to read JPEG files, but over time became increasingly dissatisfied as we discovered more and more issues. Eventually we wrote our own JPEG Decoder which fixes those issues and is now available as part of JDeli.
What is JPEG?
It is commonly used for digital images as it gives you high quality images. One main feature of JPeg is that it enables you to choose between quality and file size; you can sacrifice quality for a smaller file or vice versa.
How to read JPEG images in Java?
Here are some code examples using Image IO, JAI and JDeli to read JPEG.
File jpegFile = new File("jpegImage.jpg"); BufferedImage image = ImageIO.read(jpegFile);
RenderedImage image = JAI.create("fileload", "test1.jpeg");
You can easily replace ImageIO (and get much better support for JPEG files) by just changing ImageIO.read to JDeli.read:
//Read Image (can also be OutputStream or byte array) File jpegFile = new File("jpegImage.jpg"); BufferedImage image = JDeli.read(jpegFile);
Or you can use the JDeli JpegDecoder directly:
JpegDecoder decoder = new JpegDecoder(); BufferedImage image = decoder.read(rawImageBytes);
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
This article is part of our series on reading and writing image files in Java
IDRsolutions develop a Java PDF library, a PDF forms to HTML5 converter, a PDF to HTML5 or SVG converter and a Java Image Library that doubles as an ImageIO replacement. On the blog our team post about anything interesting they learn about.