This quick tutorial is presented to shed light on how to compress image in Java. It will share environment configuration information, necessary imports for the process, detailed steps to be performed, and a sample Java code to compress image. We will use a JPEG image to compress as a sample however you can try other types as well like PNG, TIFF, etc.
Steps to Compress Image in Java
- Establish the environment to use Aspose.Imaging from the Maven repository
- Import the necessary classes to be used in the code
- Load the sample image file into the Image class object that needs to be compressed
- Instantiate an object of JpegOptions to customize the output compressed image
- Set properties like Color Type and Compression Type in the JpegOptions object
- Save the output compressed image using the specified configurations
These steps guide how Java compress image by sharing environment configuration and usage of main classes required to accomplish the task. A step-by-step approach is followed by first loading the source image file that is to be compressed and then initializing the JpegOptions class object that is used to configure the output image by setting the color type and compression type.
Code to Compress Image in Java
These statements in Java compress image size by using JpegOptions class properties like color type is set to Grayscale that reduces image size prominently. Similarly, you can set bits per channel, file comments, image quality, resolution unit, and palette to name a very few. You can save the output file to OutputStream, a physical file on disk, and also can save the image in the defined bounding rectangle.
This tutorial has shown us how to compress image in Java. If you are interested in learning other features like resizing images, refer to the article on how to resize image using Java.