ImageMagick - Alpha Mask on transparent background

535 Views Asked by At

I want to composite some pngs onto one png using Imagemagick.

One of the images (b_0_1.png) is a mask. I need to apply this using additive composition.

But there is a problems with the background in the result, which should be transparent, but has a black square.

Here is my command:

magick -size 256x256 canvas:transparent \
  img/a_0_0.png -geometry +111+64 -compose over -composite \
  img/b_0_1.png -geometry +94+48 -compose plus -composite \
  img/c_0_0.png -geometry +108+88 -compose over -composite \
  img/d_0_0.png -geometry +102+62 -compose over -composite \
png32:result.png

Result: https://picr.ws/i/6WT

The black region should be transparent.

Images: http://s000.tinyupload.com/index.php?file_id=91925640425537122879

2

There are 2 best solutions below

2
fmw42 On

In ImageMagick, you could do

magick -size 256x256 canvas:transparent \
-channel rgb \
img/a_0_0.png -geometry +111+64 -compose over -composite \
img/b_0_1.png -geometry +94+48 -compose plus -composite \
img/c_0_0.png -geometry +108+88 -compose over -composite \
img/d_0_0.png -geometry +102+62 -compose over -composite \
png32:result.png


enter image description here

ADDITION: I think this is what you want from your comment.

magick -size 256x256 canvas:transparent \
img/a_0_0.png -geometry +111+64 -compose over -composite \
\( img/b_0_1.png -alpha opaque -alpha copy \) -geometry +94+48 -compose plus -composite \
img/c_0_0.png -geometry +108+88 -compose over -composite \
img/d_0_0.png -geometry +102+62 -compose over -composite \
png32:result.png


enter image description here

0
GeeMack On

Using ImageMagick 7 you could use a command like this...

magick -background none \
   \( -page +111+64 a_0_0.png \) \
   \( -page +94+48 b_0_1.png -alpha copy -set compose plus \) \
   \( -page +108+88 c_0_0.png \) \
   \( -page +102+62 d_0_0.png \) \
   -page 256x256 -flatten png32:result.png

That would set the paging geometry on each sub-image within their own parentheses.

Inside the parentheses with the mask image "b_0_1.png", the "-alpha copy" gets rid of the black, and the "-set compose" applies the compose method "plus" to that individual image.

Then the page size is set at 256x256, and all the parts are flattened and located according to their page geometry. Since the background setting is "none", the transparent canvas is created when the sub-images are flattened.

The compose method "over" is the default, so it's used on the images with no set compose method. The mask image is flattened using the compose method "plus".

I tested this with IM6 on bash and with IM7 on Windows. I changed my IM6 bash "convert" to "magick" for this IM7 example. It should work exactly the same with either version.