In this article, I will show you how to read JPEG images in Java using ImageIO and JDeli. We also have a related article covering how to write JPG files in Java.
ImageIO is able to handle most JPEG files but does not fully implement the spec. If you want more complete JPEG support, JDeli has been built up to provide this.
What is JPEG?
JPEG works best for colour images. It is commonly used for digital camera 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.
The file name extension for JPEG files are:
.jpg or .jpeg
How to read a JPEG image in Java with ImageIO
Step 1 Create a File, InputStream or URL Object pointing to the JPEG.
Step 2 Pass the value into ImageIO which will convert to a BufferedImage.
BufferedImage image = ImageIO.read(jpegFileOrInputStreamOrURL)
How to read a JPEG image in Java with JDeli
Step 1 Add JDeli to your class or module path (download the trial jar).
Step 2 Create a File handle, InputStream pointing to the raw JPEG image. You can also use a byte containing the image data.
Step 3 Read the JPEG image into a BufferedImage
BufferedImage image = JDeli.read(jpegFileOrInputStreamOrByte);
Why use JDeli to read JPEG?
JDeli offers a range of advantages over ImageIO and alternatives, including:
- prevents heap related JVM crashes
- more complete implementation of JPEG format
- improve read performance
- supports threading
- superior image scaling algorithms