Javatpoint Logo
Javatpoint Logo

How to Compress Image in Java Source Code?

Image compression allows us to reduce the size of an image file without significantly compromising its visual quality. There are two types of compression. First, we use lossy compression to accept a reduced image quality while achieving a much smaller file size. For instance, we have JPEG and WebP formats for lossy compression. Second, we use lossless compression to preserve data and information during compression. For example, PNG and GIF formats are used during lossless compression.

Now, we will focus on lossy compression using the JPEG format, as it is the most used format on the internet. Afterward, we will check how to compress PNG images, known as PNG image optimization.

Compressing Image in Java

First, we'll use Java Image I/O's built-in API for reading and writing images. It supports various image formats, including JPEG, PNG, BMP, and GIF. Let's see how to compress an image using Java Image I/O.

First, we are reading the image from the resources file. Then, we create an ImageWriter for the JPG format, setting this writer's output file. Before we can write the image, we create the ImageWriteParam bject to define the compression mode and the compression quality to 50%. Finally, we write the image, close the output stream, and clean the writer.

For example, by compressing an example image by 50%, we almost reduced the file size from 790KB to 656KB, a little below 83% of the initial size. Hence, the change in the quality of the picture isn't noticeable:

ImageCompressor.java

Compressing Image Using Thumbnails Library

The Thumbnails library is a straightforward and versatile library for resizing and compressing images. Let's first add the library to our pom.xml

Let's see how to compress an image using the Thumbnails class:

Output:

Image compression completed.

Compressing Images with Pngtastic Library

PNG optimization is a type of compression specifically designed for PNG images. We will use the Pngtastic library to optimize a PNG image. First, let's add the latest repository to our pom.xml

Finally, we can use the PngOptimizer class to compress a PNG file.

We use the optimize() method to let the library decide the best compression. Being a lossless compression, it is hard to reduce the size of the image significantly. Here, we reduced the size from 500 KB to 481 KB.

PNGOptimizationExample.java

Output:

PNG optimization completed.

Conclusion

We have covered two approaches to lossy compression using Java the built-in Java Image I/O API and the Apache Commons Imaging library. Then, we used the Pngtastic library to do lossless compression on PNG images.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA