coobird / thumbnailator

Thumbnailator - a thumbnail generation library for Java
MIT License
5.14k stars 784 forks source link

Is there some methods to determine the size of the compressed image? #170

Closed MA-Aaron closed 3 years ago

MA-Aaron commented 3 years ago

Hi,

I'm using this fantastic library in my project to compress images. May I know is it possible to determine the size of the output image? For example, compressing every image to 200k.

Kind Regards, Aaron

coobird commented 3 years ago

Not with Thumbnailator.

There's no good way to determine the output image size before compressing the image. Even after the compressed image is created, it's basically a trial-and-error process, since the Java Image I/O API (which Thumbnailator relies on) only provides a 0.0f to 1.0f range of compression levels. As such, it's going to be difficult (if not impossible) to hit a particular file size. One could repeat a trial-and-error method to achieve the "closest" value, but I wouldn't count on it.

I'd guess the most difficult scenario would be trying to target a size that's larger than what's achieved at the lowest compression quality settings. Unlike streams of data like audio or video which have use cases where a particular bit rate needs to be targeted (for connection speeds; sometimes you end up with padding to forcefully achieve larger values than necessary), images don't have those strict size requirements.