Page 1 of 1

Composite, then crop to smaller of two original images

Posted: 2017-06-28T10:06:55-07:00
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?

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

Posted: 2017-06-28T10:13:22-07:00
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

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

Posted: 2017-06-28T10:20:00-07:00
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

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

Posted: 2017-06-28T13:20:23-07:00
by wdmartin
Wonderful! That worked perfectly. Thanks very much to both of you.