Composite, then crop to smaller of two original images

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
wdmartin
Posts: 2
Joined: 2017-06-28T09:52:25-07:00
Authentication code: 1151

Composite, then crop to smaller of two original images

Post by wdmartin »

I have several hundred PNG images of widely varying size, and a background image large enough to fit all of them. I would like to superimpose the smaller images on top of the larger one, then discard any of the background image that exceeds the bounds of the smaller original image.

In past when I've done this, I have used a basic composite command:

Code: Select all

composite source.png background.jpg output.jpg
And then I've opened them all in Paint.net and manually cropped them one at a time, which is imprecise and takes HOURS.

I know you can do this by specifying the exact geometry on the command line. But none of the PNGs have the same dimensions, and I really don't see that it would save me any time to manually work out all those hundreds of different commands compared to cropping manually.

Is there a way to tell ImageMagick to just stick the smaller images on top of the larger ones and discard any pixels outside the bounds of the smaller one?
snibgo
Posts: 12159
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: Composite, then crop to smaller of two original images

Post by snibgo »

This composites "small" on "background", with output the same size as "small":

Code: Select all

convert small.png background.png -compose DstOver -composite out.png
snibgo's IM pages: im.snibgo.com
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Composite, then crop to smaller of two original images

Post by fmw42 »

I assume your small.png has a non-opaque alpha channel; otherwise, it will just cover the background and trim so that all you have is your small.png again.

So if it is transparent, then do

Code: Select all

convert small.png background.png -gravity center -compose dstover -composite out.png

See
http://www.imagemagick.org/Usage/compose/#compose
http://www.imagemagick.org/Usage/compose/#duff-porter
http://www.imagemagick.org/Usage/layers/#convert
wdmartin
Posts: 2
Joined: 2017-06-28T09:52:25-07:00
Authentication code: 1151

Re: Composite, then crop to smaller of two original images

Post by wdmartin »

Wonderful! That worked perfectly. Thanks very much to both of you.
Post Reply