Compress PNG images using ImageMagick
To compress a JPEG image, I can do:
$thumb = new Imagick();
$thumb->readImage("url");
$thumb->setImageCompression(Imagick::COMPRESSION_JPEG);
$thumb->setImageCompressionQuality(80);
However, I need to also compress PNG images (preserving alpha transparency) to reduce the size. Is there a way to do this with ImageMagick?
pngquanteffectively quantizes or reduces the number of colors in the image until a noticeable drop in quality. You can try something similar in ImageMagick like this ...
First, using the embedded image rose:, check the number of colors in the image - this is 3.019:
convert rose: -format %k info:
3019
and make from it PNGand check the size - it's 6.975 bytes
convert rose: rose.png
ls -l rose.png
-rw-r--r--@ 1 mark staff 6975 5 Sep 20:57 rose.png
255 - 3,691 :
convert rose: -colors 255 rose255.png
ls -l rose255.png
-rw-r--r-- 1 mark staff 3691 5 Sep 21:02 rose255.png
64 - 2,361 .
convert rose: -colors 64 rose64.png
ls -l rose64.png
-rw-r--r-- 1 mark staff 2361 5 Sep 21:04 rose64.png
PNG -strip - , , , .
, ... , , . , PNG, -alpha background.
convert -size 512x512 xc:gray +noise random a.png # create an image of random noise
-rw-r--r--@ 1 mark staff 1576107 6 Sep 11:37 a.png # 157kB
convert -size 512x512 xc:gray +noise random -alpha transparent a.png # recreate but make transparent
-rw-r--r--@ 1 mark staff 1793567 6 Sep 11:38 a.png # 179kB, extra transparency channel
convert -size 512x512 xc:gray +noise random -alpha transparent -alpha background a.png # make all transparent pixels black
-rw-r--r--@ 1 mark staff 1812 6 Sep 11:38 a.png # Presto!


