简体   繁体   English

不使用Bitmap#compress()方法将JPEG图像压缩到特定质量级别

[英]Compress JPEG image to specific quality level without using Bitmap#compress() method

I want to compress a Bitmap (JPEG image) to quality 64 , the result with be stored in a byte array. 我想将位图(JPEG图像)压缩到质量64 ,结果存储在字节数组中。 Previously I can achieve this with Bitmap#compress() method: 以前,我可以使用Bitmap#compress()方法实现此目的:

public static byte[] compressJPEG(Bitmap bmp, int quality) {
    if (quality <= 0)
        return new byte[0];

    byte[] array = new byte[0];
    try {
        ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, quality, bmpStream);
        array = bmpStream.toByteArray();
        bmpStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return array;
}

But the result byte array (with the same input image file) is different when I run this on different devices. 但是当我在不同设备上运行时,结果字节数组(具有相同的输入图像文件)是不同的。 (May be because it use nativeCompress() internally) (可能是因为它内部使用了nativeCompress()

After checking, I find out the different is in Huffman Table(s), SOS & image data parts, see this: Diff check between 2 image photos 检查后,我发现霍夫曼表,SOS和图像数据部分有所不同,请参见: 在2张图像照片之间进行差异检查

So how can I compress JPEG image to specific quality level without using Bitmap#compress() method? 那么如何在不使用Bitmap#compress()方法的情况下将JPEG图像压缩到特定的质量级别? Because I really want the result byte array to be similar in structure. 因为我真的希望结果字节数组在结构上相似。

There is no concept of "quality level" in JPEG. JPEG中没有“质量级别”的概念。 It is a shorthand that some encoders use to select quantization tables. 一些编码器用来选择量化表的简写形式。 There are a number of variables in JPEG compression, including the type and breakdown of scans, samples, huffman table selection, and quantization table selection. JPEG压缩中有许多变量,包括扫描的类型和分类,样本,霍夫曼表选择和量化表选择。 If any of those are different in the encoder you use, you are going to get different output. 如果您使用的编码器中的任何一个不同,您将获得不同的输出。 It's the nature of the beast. 这是野兽的天性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM