Java 图像压缩

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22812325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:04:58  来源:igfitidea点击:

Java Image compression

javaimage-compression

提问by ali muhammad

From our application we fetch images (jpeg/png) from a third party service, after download we want to save these images as compressed.

从我们的应用程序中,我们从第三方服务获取图像 (jpeg/png),下载后我们希望将这些图像保存为压缩文件。

Can any one please guide how to compress images in Java ?

任何人都可以指导如何在 Java 中压缩图像吗?

回答by Marco13

JPG and PNG images already arecompressed, so it's not entirely clear what your intention is. However, in general, you can write images with ImageIO:

JPG 和 PNG 图像已压缩,因此您的意图尚不完全清楚。但是,通常,您可以使用以下命令编写图像ImageIO

ImageIO.write(image, "jpg", outputStream);

(or "png", analogously). By default, this does not allow you to select the compression level(that is, the trade-off between file size and image quality). In order to write a JPG file with a different than the default compression, you can use a utility method like this:

(或"png",类似地)。默认情况下,这不允许您选择压缩级别(即文件大小和图像质量之间的权衡)。为了编写与默认压缩不同的 JPG 文件,您可以使用如下实用方法:

public static void writeJPG(
    BufferedImage bufferedImage,
    OutputStream outputStream,
    float quality) throws IOException
{
    Iterator<ImageWriter> iterator =
        ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter imageWriter = iterator.next();
    ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
    imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    imageWriteParam.setCompressionQuality(quality);
    ImageOutputStream imageOutputStream =
        new MemoryCacheImageOutputStream(outputStream);
    imageWriter.setOutput(imageOutputStream);
    IIOImage iioimage = new IIOImage(bufferedImage, null, null);
    imageWriter.write(null, iioimage, imageWriteParam);
    imageOutputStream.flush();
}