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?
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With