Search code examples
phpimagemagickjpegimagick

imagick - Progressively low compression quality


I'm trying to calculate the best compression quality for an image to be less than 150kB. But Imagick makes me sick...

Here's my code :

<?php
// {...}
// $white is my image
// self::THUMBNAIL_SIZE_KO is 150

$quality = 100;
$white->setImageFormat('jpg');
$white->setImageCompression(Imagick::COMPRESSION_JPEG);
$white->setCompressionQuality($quality);
$data = $white->getImageBlob();
var_dump(strlen($data));
while(strlen($data) > self::THUMBNAIL_SIZE_KO * 1024 && $quality > 0){
    $quality--;
    $white->setCompressionQuality($quality);
    $data = $white->getImageBlob();
    var_dump($quality);
    var_dump(strlen($data));
}

$this->_canvas = $white;

I made var_dumps to control the size in bytes of the rendered image. But it's alaways the same size :

// var_dump rendered :

int 167963
int 99
int 167963
int 98
int 167963
int 97
int 167963
int 96
int 167963
int 95
int 167963
int 94
int 167963
int 93
int 167963
// etc.

Do you know why Imagick has it strange behaviour, or if there is something wrong with my code ?

Thanks ! :)


Solution

  • It appears your image is an existing image, therefore you need to use setImageCompressionQuality not setCompressionQuality, because the latter only works for new images created with Imagick::newPseudoImage.

    $white->setImageCompressionQuality($quality);