Converting PNG32 file to PNG8 without losing alpha channel


I'm using Linux and have no access to any of Adobe's 'fancy' programs.

I'm trying to convert an existing PNG32 image with alpha channel to PNG8. I have tried the following methods:

  • convert original.png PNG8:new.png – Horribly distorts the image and preserving only binary alpha (Not Indexed alpha)
  • GIMP – Fails as well, but produces better quality (good color quantizer) than ImageMagick.
  • pngcrush -rem alla -reduce -brute original.png new.png – Made the image smaller but didn't take quantization into account (Image has less than 256 colors), so output was still PNG32.

What else can I try?

Best Answer

  • This PHP script does the trick with libgd:

    if(!isset($argv[1]) || !is_readable($argv[1])) {
        echo "Creates an 8-bit PNG from a 32-bit PNG\n\n";
        echo "Usage:\n";
        echo "\t" . $argv[0] . " input.png > output.png\n";
        echo "\t" . $argv[0] . " input.png output.png\n";
    $inFile = $argv[1];
    $outFile = $argv[2] or STDOUT;
    $inImage = imagecreatefrompng($inFile);
    $outImage = imagecreate(imagesx($inImage), imagesy($inImage));
    imagecopy($outImage, $inImage, 0, 0, 0, 0, imagesx($inImage), imagesy($inImage));
    imagepng($outImage, $outFile);

    Dump that into a file and run it as:

    php convert.php input.png output.png