Skip to content
MagickCmd › ImageMagick transparency and alpha channel

ImageMagick transparency and alpha channel

Make a colour transparent, flatten alpha onto a background, remove the alpha channel, or extract it as a mask. Includes the fix for transparent PNGs turning black in JPEG.

Make a colour transparent

magick input.png -fuzz 15% -transparent white output.png

The -fuzz tolerance is what makes this usable — without it, only pixels that are exactly the target colour are affected, and anti-aliased edges leave a visible fringe.

This works well on flat, synthetic backgrounds — logos, screenshots, product shots on pure white. On a photograph it will punch holes through anything else near that colour: white clouds, a white shirt, a highlight on skin. Raise -fuzz gradually and inspect the result; 12–20% is a reasonable range.

Output must be PNG or WebP. Writing to JPEG silently discards the transparency you just created.

Removing a background properly

For real photographs, colour-key removal is the wrong tool. ImageMagick has no subject-detection, so you want a dedicated background-removal model (rembg and similar) and then ImageMagick for whatever comes after.

Flatten transparency onto a background

magick input.png -background white -alpha remove -alpha off output.jpg

This is the correct fix for the "transparent PNG became a black JPEG" problem. -alpha remove composites the image against -background; -alpha off then drops the now-redundant channel so the file is smaller.

-flatten does something similar, but it also merges layer offsets — if the file has a virtual canvas from an earlier crop, your image can move unexpectedly. Prefer -alpha remove unless you specifically want the layer behaviour.

Set overall opacity

magick input.png -alpha set -channel A -evaluate multiply 0.5 +channel output.png
  • -alpha set creates an alpha channel if the image has none.
  • -channel A restricts the next operator to alpha only.
  • +channel switches back. Forgetting this is a classic bug — every later operator would keep touching alpha alone.

Extract the alpha channel as a mask

magick input.png -alpha extract mask.png

You get a grayscale image where white is opaque and black is transparent. Useful for inspecting why an edge looks wrong, and for feeding masks into other tools.

Check whether an image has transparency

magick identify -format '%[opaque] %A\n' input.png

%[opaque] reports true when the image has no transparent pixels; %A reports whether an alpha channel is present at all. The two can disagree — a file can carry an alpha channel that happens to be fully opaque.

Replace one colour with another

magick input.png -fuzz 10% -fill '#0d9488' -opaque white output.png

-opaque is the colour-replacement counterpart to -transparent.


Related

Copied