2

I have two images:

  • a.jpg
  • b.jpg

Both images are square (100x100 pixel). I want to cut a circle with a radius of 50 from image a.jpg and paste it in the middle of image b.jpg. I want to save the result in c.jpg.

How can I do this with Linux command line tools? I need to do it within a shell script.

2 Answers 2

5

Many different techniques can be used. ImageMagick has FX language that can perform complex calculations.

convert a.jpg b.jpg -fx 'Wi=w/2; Hi=h/2; hypot(Wi-i, Hi-j) < 50 ? u : v' c.jpg

For example...

convert -size 100x100 PLASMA: a.jpg

a.jpg

convert -size 100x100 GRADIENT:LIME-ORANGE b.jpg

b.jpg

convert a.jpg b.jpg -fx 'hypot(50-i, 50-j) < 50 ? u : v' c.jpg

c.jpg

Update with another technique.

A faster approach can be leveraging image mask(s) of the shape you wish to crop, and compose/composite it between both images. It'll require a format that supports alpha channels, but only for the initial work. For example...

Create a circle mask, and copy values to alpha channel.

convert -size 100x100 xc:White -fill Black \
        -draw 'circle 50 50 50 5' -alpha Copy mask.png

mask.png

convert \( a.png mask.png -alpha Set -compose Dst_Out -composite \) \
        b.png -compose Dst_Atop -composite c.png

c.png

1

Eric's approach is much more succinct, and probably preferable, but here is another way anyway. I am being very environmentally aware and recycling ;-) his start images:

magick b.jpg \( a.jpg \( +clone -threshold 101% -fill white -draw "circle 49,49, 49,99"  \) -channel-fx '| gray=>alpha' \) -flatten result.png

That says... "Load b.jpg as the background. Load a.jpg and then create a transparency mask by cloning the entire a.jpg setting it black and drawing a white circle in it and pushing it into the alpha channel. Then flatten that over the top of b.jpg".

The result is the same as Eric's.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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