DisgruntledGoat
DisgruntledGoat

Reputation: 72530

ImageMagick: how to reduce colors but keep transparency?

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.

Upvotes: 6

Views: 6560

Answers (2)

sschuberth
sschuberth

Reputation: 29821

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.

Upvotes: 7

toc777
toc777

Reputation: 2697

Have you tried -colorspace transparent to preserve the Alpha channel?

Upvotes: 0

Related Questions