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>
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!