How to predict image size in megabytes after JPEG-compression

Viewed 1361

For example, we have file.jpg with size 5Mb. And our aim is to compress it to size 2Mb. There is souch methodin SDK: Bitmap.compress(Bitmap.CompressFormat format, int quality, OutputStream stream).

Is there any variant to calculate target quality value before compression?

2 Answers

You cannot predict the final output of JPEG compression.

The only option for you would be to perform some brute forcing, but in an optimized way.

Generally JPEG compresses the bitmap in the ratio 10:1.

So if your image resolution is 4096*4096, it requires 4096*4096*2 raw bytes (2 because RGB_565 is used), which equals 33554432 bytes = 32MB raw. Assuming 10:1 compression, It will take 3.2MB.

But it is greater than 2MB! So you will need to make the quality to 2/3.2=62.5℅. So first try with 62℅ as a quality parameter.

Now compress the image to a ByteArrayOutputStream and check the length of the byte array. If the length of the array is less than 2*1024*1024=2097152, it is okay. Otherwise you should try decreasing the quality eg by 10℅ to 52℅ and try again.

According to this, quality is a int that Hint to the compressor, 0-100. When 0 meaning compress for small size and 100 meaning compress for max quality. But some formats like PNG which is lossless, will ignore this quality setting. So, i think it's depend on your goal. If you want to get the maximum quality in minimum size then you need to resize & implement high number of quality.

Hope, it can help you.

Related