Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageMagick: how to reduce colors but keep transparency?

Tags:

imagemagick

I have some PNG files I wish to convert to 256 colors (i.e. GIF-like). Each image has transparency, but when I try to convert I always end up with a black background on the resulting image.

Here is my current command:

convert file.png -colors 255 file256.png

I'm using 255 colors because I read that you need one color for the alpha channel (though I don't think that should apply to PNGs). I've tried many other options such as -background none, -channel RGBA and -matte but nothing is working at all.

Interestingly, this command did work when converting to grayscale:

convert file.png -channel RGBA -matte -colorspace gray file256.png

It kept the transparent background. But replacing -colorspace gray with -colors 256 doesn't work.

like image 544
DisgruntledGoat Avatar asked Feb 03 '11 13:02

DisgruntledGoat


1 Answers

The reason to use 255 instead of 256 colors is that one color needs to be reserved for "binary" / "boolean" transparency, i.e. all pixels of that color are interpreted as completely transparent. There (usually) is no such thing like an alpha channel with 256-color / palette-based images. For reference, you may want to read the ImageMagick usage sections about Color Quantization and Transparency and GIF Boolean Transparency. That said, this should convert your 32-bit true-color PNG with alpha channel to an 8-bit PNG with palette where all pixels that are fully transparent in the input image are also fully transparent in the output image:

convert file.png png8:file256.png

The png8 instructs ImageMagick to write a GIF-like "8-bit indexed with optional binary transparency" PNG and implies to use 255 "real" colors.

like image 65
sschuberth Avatar answered Oct 10 '22 23:10

sschuberth