Android image encoding with maximum size limit

I need to encode an image in JPEG format, and the maximum file size is 300 K and send it as an array of bytes. I am doing the encoding:

ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); image = baos.toByteArray(); 

Do you know how to limit the file size to 300K? perhaps the solution is to lower the image quality, but sometimes (when the image is smaller) I may not need it. Thanks

+4
source share
2 answers

Repeatedly compressing with downstream โ€œqualityโ€ values โ€‹โ€‹to the received byte [] length <= 300 KB. There is no shortcut (AFAIK) in this, but you can carefully select quality values โ€‹โ€‹and limit yourself, say, to a maximum of 4 compressions.

+4
source

The quick answer is to use a trial and test solution to find a compression value that gives you a value close to less than 300k.

The file sizes for JPEGs are highly dependent on the details of the image, so if you don't take pictures with the same detail (not all black images, etc.), then the best compression rating will be different.

Maybe use a binary search algorithm to find a good solution? Start at 50, then if it's too big, go down to 25, otherwise to 75. Then when you go in, say, 270-300 just stop?

+2
source

Source: https://habr.com/ru/post/1339667/


All Articles