简体   繁体   中英

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

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.

These are the default compression methods used for the following common image formats:

PNG:  Imagick::COMPRESSION_ZIP
JPEG: Imagick::COMPRESSION_JPEG
GIF:  Imagick::COMPRESSION_LZW

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM