1

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 ! :)

Thaledric
  • 415
  • 1
  • 6
  • 16
  • As well as using the correct function, you could use a "dividing" approach to get the appropriate compression quality faster than just a "step" approach: http://stackoverflow.com/a/19639344/778719 – Danack Apr 03 '16 at 16:24
  • Great idea, I will do this ! Thanks ! – Thaledric Apr 03 '16 at 17:37

1 Answers1

2

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);
MrCode
  • 59,851
  • 9
  • 76
  • 106