Smart images resize by maximum file size in Java

Imagine we have application which allows image storage/processing/sending, and there is a requirement for automatic reduce of input image size to X bytes.

There are many ways and libraries to resize an image, but I was not able to find something which achieves the described requirement (at least in Java). All libraries resize/compress an image by target resolution, quality, format etc., without assuring the required maximal size.

So I wrote my own small library which extends ImageIO and ImgScalr libraries to achieve my goal.

The main function is resizeImageByFileSize, which gets image and desired file size and returns the image of the desired file size.

Most image resize libraries perform resize based on desired image resolution or size in pixels.
In my case, current file size is known, current resolution is known, desired file size is known. So the problem is reduced to calculating correct target image resolution which will give us the desired file size.

Continue reading