In this article, I will show you how to write JPEG Images in Java using imageIO, JAI and JDeli (a complete ImageIO replacement and JPG converter from IDRsolutions). Firstly I will start with explaining what is JPEG.
What is JPEG?
JPEG stands for
"Joint Photographic Experts Group,” and is a file format for compressed images. It uses lossy compression for digital images and is best for saving photographs and paintings of realistic scenes with smooth variations of tone and color (where you do not notice the missing details).
Because JPEG images are not limited to a certain amount of color and contain colorful, high-resolution image data, JPEG is frequently used for storing and transmitting photographic images on the Web and is one of the most common format saved by digital cameras. There is a tradeoff between size and quality.
The file name extensions for JPEG files are:
Example Java code to write JPEG images in Java:
Here are some code examples using Image IO, JAI and JDeli to save a BufferedImage to a JPEG
– Using Image IO
Javadoc and included in JDK
//Write Image (can also be OutputStream) File myNewJPegFile=new File("ImageAsJPeg.jpg"); ImageIO.write(myBufferedImage, "jpg", myNewJPegFile);
//Write Image File myNewJPegFile=new File("ImageAsJPeg.jpg"); JAI.create("filestore", myBufferedImage, myNewJPegFile, "JPEG");
You can easily replace ImageIO (and get much better support for JPEG files) by just changing ImageIO.write to JDeli.write.
//Write Image (can also be OutputStream) File myNewJPegFile=new File("ImageAsJPeg.jpg"); JDeli.write(myBufferedImage, "jpg", myNewJPegFile);
Or you can use the JDeli JpegEncoder directly:
//Write Image OutputStream os = new FileOutputStream(new File("ImageAsJPeg.jpg")); JpegEncoder encoder = new JpegEncoder(); encoder.write(myBufferedImage, os); os.flush(); os.close(); JDeli can read and write a very wide range of image formats. Here is the <a href="https://support.idrsolutions.com/hc/en-us/articles/360026121951-Convert-image-file-formats">full list on Image file conversions</a> supported.
I hope you found this useful. You can find more tutorials in our series on handling common image formats in Java, JDeli and other image libraries.