dodge
dodge

Reputation: 81

how to convert PNG32 to PNG8 via Imagick in PHP

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?

Upvotes: 4

Views: 4433

Answers (2)

pseudosavant
pseudosavant

Reputation: 7244

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");

Upvotes: 3

Greg Bulmash
Greg Bulmash

Reputation: 1947

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.

Upvotes: 14

Related Questions