Более эффективный ответ (еще более сложный), основанный на обсуждении моего другого вопроса между Данаком и мной (еще не проверял, все еще в процессе).
$filename = "test.jpg";
$image = new Imagick($filename);
// Setting your default compression
$height = $image->getImageHeight();
$width = $image->getImageWidth();
$raw_size = $height * $width;
// Imagick needs to know how to compress
$image->setImageCompression(COMPRESSION_JPEG);
$image->setImageCompressionQuality($compression_value);
// 80 compression shaves off about 40% of file size. Using that to estimate
// 1% reduction for every 2 compression. This should be refined
// as more data is gained for your specific scenario.
$compression_value = int(190/$raw_size);
// getImageLength gets the length of the file in bytes.
loop_refine($compression_value, $image);
while () {
}
// This reduces our size just a little more
$image->stripImage();
$img = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename).".tiff";
$image->writeImage($img);
function loop_refine(&$compression_value, &$image){
if ($image->getImageLength() > 95000 && $compression_value < 101){
reduce_image_size($compression_value, $image);
} elseif ($image->getImageLength() > 92000 && $compression_value < 101){
increase_image_size($compression_value, $image);
} else {
return;
}
}
function reduce_image_size(&$compression_value, &$image){
$compression_value = $compression_value + int((101 - $compression_value)/2);
$image->setImageCompressionQuality($compression_value);
loop_refine($compression_value, $image);
}
function increase_image_size(&$compression_value, &$image){
$compression_value = $compression_value - int((101- $compression_value)/4);
$image->setImageCompressionQuality($compression_value);
loop_refine($compression_value, $image);
}