Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress a PNG image with 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 keep sizes down. Is there a way to do it with ImageMagick?

like image 904
frosty Avatar asked Sep 05 '15 13:09

frosty


1 Answers

pngquant effectively quantizes, or reduces the number of colours in an image till just before there is a discernible drop in quality. You can try something similar in ImageMagick like this...

First, using the built-in rose: image, check the number of colours in the image - it is 3,019:

convert rose: -format %k info:
3019

and make a PNG of it and check the size - it is 6,975 bytes

convert rose: rose.png
ls -l rose.png
-rw-r--r--@ 1 mark  staff  6975  5 Sep 20:57 rose.png

enter image description here

Now convert the rose to 255 colours and check the size - it is down to 3,691 bytes:

convert rose: -colors 255 rose255.png
ls -l rose255.png
-rw-r--r--  1 mark  staff   3691  5 Sep 21:02 rose255.png

enter image description here

Now convert the rose to 64 colours and check the size - down to 2,361 bytes

convert rose: -colors 64 rose64.png
ls -l rose64.png
-rw-r--r--  1 mark  staff  2361  5 Sep 21:04 rose64.png

enter image description here

Another way of optimising or reducing PNG filesizes is to use -strip to strip out any metadata from images - such as the date and time the picture was taken, the camera and lens model, the name of the program that created the image and the copyright and colour profiles.

Also, worth bearing in mind... normally, the colour of transparent pixels is irrelevant because you can't see them, but uniform things generally compress better. So, it may be a good idea to make all transparent pixels the same colour when saving PNG files, by using -alpha background.

Example

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!
like image 154
Mark Setchell Avatar answered Oct 21 '22 20:10

Mark Setchell