Home > Java > javaTutorial > How to Adjust JPEG Compression Level Using ImageIO in Java?

How to Adjust JPEG Compression Level Using ImageIO in Java?

Susan Sarandon
Release: 2024-10-25 20:18:29
Original
950 people have browsed it

How to Adjust JPEG Compression Level Using ImageIO in Java?

Setting JPEG Compression Level with ImageIO in Java

When using ImageIO to save a BufferedImage as a JPEG, you may encounter the need to adjust the compression level. This parameter is not readily apparent within the basic ImageIO write method.

To set the compression level, you can access the ImageWriter directly from ImageIO. Here's an example:

<code class="java">ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpgWriteParam.setCompressionQuality(0.7f);</code>
Copy after login

Note that ImageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) is required to enable explicit quality setting. The compression quality value ranges from 0.0f (maximum compression) to 1.0f (maximum quality).

To complete the write process, use ImageWriter.setOutput to set an ImageOutputStream. While you can use the generic Object type, it's typically recommended to employ FileImageOutputStream for direct file writing or MemoryCacheImageOutputStream for output streams like ByteArrayOutputStream.

The above is the detailed content of How to Adjust JPEG Compression Level Using ImageIO in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template