Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a gray-scale image. I want to convert it into an transparent PNG, such that the black pixels (in the original image) become fully opaque, the white pixels become fully transparent, a 50% grey pixel would become 50% transparent, and so on for all the shades in between.

How can I achieve this?

(Yes, I know that this is almost the same question as Converting grayscale shades into alpha channel, but I want to know how to do this using only command line tools – e.g. ImageMagick or NetPBM.)

share|improve this question

1 Answer 1

up vote 5 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.