8

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?

Czechnology
  • 14,832
  • 10
  • 62
  • 88
  • 1
    Related reading: http://www.imagemagick.org/Usage/formats/#png_quality – Pekka Sep 18 '11 at 16:40
  • @pekka, thanks for the link! However, I'm not sure if it works the same with php. I've tried saving my images with compressions 00-99 and the *difference* in filesizes was at most about 10 %. But a simple GIMP-save pushed the size down to about one third. Is there something else I could be doing wrong? – Czechnology Sep 18 '11 at 19:03
  • 3
    I'm having the same problem... Unfortunately haven't found a good answer yet. – Joshua Burns Dec 08 '11 at 23:36

2 Answers2

3

Have a look at the first part of this answer:

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

Community
  • 1
  • 1
Kurt Pfeifle
  • 86,724
  • 23
  • 248
  • 345
  • Hi, I've already found some definitions explaining this. The trouble is that even when I've tried all possible quality values, the images are still significantly bigger that when saved with GIMP or similar app. – Czechnology Aug 21 '12 at 14:15
  • You should look at the difference of output if you use `identify -verbose a.png` for both, Gimp- and IM-generated ones. Maybe Gimp uses 8-bit depth where your ImageMagick is set to use 16-bit? Or gimp strips color profiles which where there before? Or Gimp uses a 'palette' which effectively limits the number of colors used? – Kurt Pfeifle Aug 21 '12 at 14:36
  • If you post (a link to) a sample pair of such PNGs, I could analyze the differences and maybe tell you an IM (commandline) tweak that allows you to create smaller PNGs directly from IM (and hence, from IMagick)... – Kurt Pfeifle Aug 21 '12 at 14:38
0

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!

Giedrius
  • 1,590
  • 3
  • 16
  • 27