Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert PNG32 to PNG8 via Imagick in PHP

Tags:

php

png

imagick

I want to convert PNG32 to PNG8 via the php Object Imagick. but I used setImageDepth and setImageFormat setting param to 8bit, it didn't take effect. the code like this:

$im = new Imagick($image);
$im->cropImage($cutWidth,$cutHeight,$x,$y);
$im->thumbnailImage($maxWidth, $maxHeight); 
$im->setImageDepth(8);
$im->setImageFormat('PNG8');
$im->writeImage($filename);

inputfile is PNG32, but output above remains PNG8, have other solution?

like image 924
dodge Avatar asked Dec 07 '22 15:12

dodge


2 Answers

This seems to be a known problem, so I did some research. Basically, the setImageDepth just isn't enough. You need to quanitize the image. This is a test script that worked for me...

$im = new imagick('stupid.png'); //an image of mine
$im->setImageFormat('PNG8');
$colors = min(255, $im->getImageColors());
$im->quantizeImage($colors, Imagick::COLORSPACE_RGB, 0, false, false );
$im->setImageDepth(8 /* bits */);
$im->writeImage('stupid8.png');

Came out nice.

like image 59
LetMyPeopleCode Avatar answered Dec 10 '22 13:12

LetMyPeopleCode


I know this is an old question that has already been answered but there is one other shorter way to do this that I discovered. You can force the write format by prefixing the filename with the format (e.g. png8:outputfile.png). The question example could be accomplished like this:

$im = new Imagick($image);
$im->cropImage($cutWidth,$cutHeight,$x,$y);
$im->thumbnailImage($maxWidth, $maxHeight); 
$im->writeImage("png8:$filename");
like image 37
pseudosavant Avatar answered Dec 10 '22 13:12

pseudosavant