I am currently resampling uploaded images to a static width and height. I’d like to be able to create a new copy of the image at the greatest quality below a certain file-size threshold. Currently, I’m using a very naive method – something like this:
$size = NULL;
$quality = 100;
while ($size === NULL || $size > MAX_SIZE) {
// write the image to disk using $quality
clearstatcache(TRUE, $image);
$size = filesize($image);
$quality -= 10;
}
Is there a better method for determining what quality I should use?
The resulting file size depends not only on the quality parameter, but on the image itself. Generally, it is not possible to forecast the file size exactly.
You could make a series of measurements for your typical images and create some scale which would let you guess exact quality parameter more quickly.
You could also go for binary search which would converge at good enough point after some iterations.