Optimize jpg images with php-imagick for Google Pagespeed, 1,9 KB (20 %)

Viewed 1231

I am using php-Imagick on my vps maschine.
Using this php script for optimizing uploaded images:

$quality = 70;
$img = new Imagick();
$img->readImage($file);
$img->setImageBackgroundColor('white');
$img = $img->flattenImages();
$img->setImageFormat('jpg');
$img->resizeImage($final_width, $final_height, Imagick::FILTER_LANCZOS, 1);

$img->optimizeImageLayers();
$img->setImageCompression(Imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality($quality);
$img->stripImage();
$newFile = substr_replace($file, $anhang, strrpos($file, "."), 0);
$newFile = preg_replace('/\\.[^.\\s]{3,4}$/', '.jpg', $newFile);
$img->writeImage($newFile);

OPTIONAL setting bestfit:

$info = getimagesize($file);
list($width_old, $height_old) = $info;
$factor = $width/$width_old;
$factor2 = $height/$height_old;

$final_width = $width;
$final_height = round( $height_old * $factor );

if($final_height >= $height){
    $final_height = $height;
    $final_width = round( $width_old * $factor2 );

    }

I have already tested png images, which get converted into jpg images. According to google pagespeed they are 100% OK.
But all jpg files that I tested need optimization of 20%.
I did an example with a stonehenge image that I found on Google. According to Google:

Compression could save 1.9 KB (20%).

So I downloaded and compared both, but couldn't find any difference in quality. I uploaded both on file-upload https://www.file-upload.net/download-12807399/image.rar.html (couldn't upload them on a imagehoster, because that would change both ;D)

So is there something missing in my script ? How can I optimize the image for the last 20% ?

EDIT: In another example, I noticed that it must be something with the colors, because the Imagick image has less orange and bright colors. Maybe I have to use less bit-depth or something like that?
Edit2: I tried to convert into srgb, no changes...

Edit3: Finally found solution:

$img->setSamplingFactors(array('2x2', '1x1', '1x1'));
0 Answers
Related