Convert grayscale image into alpha channel image in unix shell
Ooookay. After plenty of googling, and reading for more of the ImageMagick manual than I actually care for, here's the answer. Given that you have a grayscale image called source.png
, here are my commands.
To make the make the black pixels transparent and keeps the white pixels as they are, run this command:
convert source.png -alpha copy -fx '#fff' result.png
To instead make the white pixels transparent while keeping the black as-is, use:
convert source.png -alpha copy -channel alpha -negate +channel -fx '#000' result.png
Let's explain that last command a bit more thoroughly:
convert
– Is the ImageMagic command (one of several)source.png
– The greyscale source image.-alpha copy
– Copy contents of the previous file into the alpha channel.-channel alpha
– Specify that following operators only should affect the alpha channel.-negate
– Invert the alpha channel (will, because of the previous-chanel alpha
not affect any other part of the image).+channel
– Specify that following operators only should should affect the color channels, and no longer modify the alpha channel. (This is the default, and therefore we need not provide it in the first, simpler example.)-fx '#000'
– Replace color channel contents with black pixels. (Because of+channel
the alpha channel will not be affected).
It is quite important to include that final -fx
option, otherwise all semi-transparent pixels in generated image will retain colors. (Since these pixels are half-transparent, it might not be obvious, but the end result is not what one expect.)
I found the list of ImageMagick options quite useful.