Skip to content
Advertisement

php imagick won’t save PNG compressed but shows compressed in browser

I have the following code in PHP to take the screenshot of first page of the PDF.

    $name = getcwd()."\testfile";
    $img = new imagick();
    $img->setResolution(200,200);
    $img->readImage($name.'.pdf[0]');
    $img->setImageResolution(100,100);
    $img->resampleImage(100,100,imagick::FILTER_LANCZOS,1);
    $img->setImageCompression(Imagick::COMPRESSION_ZIP );
    $img->setImageCompressionQuality('0');
    $img->setImageFormat('png8');
    $img->writeImage($name.".png");
    header("Content-type : image/png");
    echo $img;

This code produces the PNG of 62kb only in the Google Chrome’s Resource monitor tab. But the image which is written by Imagick() is above 114kb. Just to make sure image isn’t compressed and or any other issues i have used a online service called TinyPNG and they compressed the image shrinking it to exactly 62kb i get in browser…

What could be wrong in this code? Also i am using PNG8 format because thats more efficient.

Best

Ahsan

Advertisement

Answer

I think this is caused by your writeImage statement. If you write a PNG image without specifying png8: specifically in the filename your image will not be stored in that format. In essence setImageFormat will only affect when you retrieve the image as a string (echo $img).

If you do the following:

$img->writeImage ('png8:' . $name . ".png");

it should be stored as a png8. You can verify this with identify -verbose and checking the Depth / Channel Depth.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement