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?
Setting grayscale with
-set colorspace Gray
won't reduce the PNG's file-size unless these options are also used:This makes 8-bit grayscale with highest PNG compression. Adding those options reduced my image size 3×, because now it's one channel (grayscale) whereas before it was 3 (RGB).
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:and make a
PNG
of it and check the size - it is 6,975 bytesNow convert the rose to 255 colours and check the size - it is down to 3,691 bytes:
Now convert the rose to 64 colours and check the size - down to 2,361 bytes
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