PHP+Imagick - PNG Compression

2019-01-26 10:52发布

问题:

How do I efficiently compress a PNG? In my case, the images are small grayscale images with transparency.

Currently I'm playing with this:

// ...

$im->setImageFormat('png');
$im->setImageColorspace(\Imagick::COLORSPACE_GRAY);
$im->setImageCompression(\Imagick::COMPRESSION_LZW);
$im->setImageCompressionQuality(9);
$im->stripImage();
$im->writeImage($url_t);

As Imagick doesn't offer COMPRESSION_PNG, I've tried LZW but there's almost no change in the filesize (usually it's even bigger than before).

If I open the image in GIMP and simply save it, the filesize gets drastically reduced (e.g. 11,341 B --> 3,763 B or 11,057 B --> 3,538).

What is the correct way of saving a compressed PNG with Imagick?

回答1:

Have a look at the first part of this answer:

  • Convert multipage PDF to PNG and back (Linux)

It explains the meaning + syntax of ImageMagick's -quality setting for PNGs.



回答2:

I'm definitely not sure if it is correct way to save PNG, but my way is:

$im->setImageCompression(\Imagick::COMPRESSION_UNDEFINED);
$im->setImageCompressionQuality(0);

This gives me perfect quality of the image and file size very similar to PS6 saved 'Save for Web'. Sometimes even smaller sizes!