将图像压缩为 100 KB

Compress image to 100 KB

提问人:KripDo 提问时间:10/12/2023 更新时间:10/12/2023 访问量:63

问:

我需要将图像压缩到 100 kB,以便将其上传到 Active Directory。我写了这段代码,但它不适用于所有图像尺寸。在循环的某个迭代中,它只是保留相同的图像大小。

private static byte[] compressImage(byte[] originalImage) throws IOException {
    ByteArrayInputStream originalImageStream = new ByteArrayInputStream(originalImage);
    ByteArrayOutputStream compressedImageStream = new ByteArrayOutputStream();

    Thumbnails.of(originalImageStream)
            .scale(1)
            .outputQuality(COMPRESSION_QUALITY)
            .toOutputStream(compressedImageStream);

    byte[] compressedImageBytes = compressedImageStream.toByteArray();
    if (compressedImageBytes.length <= MAX_SIZE_IN_BYTES) {
        return compressedImageBytes;
    }
    return compressImage(compressedImageBytes);
}

我尝试用纯 Java 编写,出现了同样的问题

Java 映像 文件 IO

评论

0赞 Federico klez Culloca 10/12/2023
在某种程度上,你可以进一步压缩东西,除非你降低质量。即便如此,也有较低的限制。
0赞 roediGERhard 10/12/2023
有趣的是,这段代码甚至可以正确退出,因为我希望当图像不再“可压缩”时,它永远不会离开循环。

答: 暂无答案