18

Is there are way to automatically resize the overlay image according to background size when overlaying images using ImageMagick? I am using the following code now:

composite overlay.jpeg background.jpeg result.jpeg

The problem is that sometimes overlay and background are of different sizes, and I'd like to resize overlay accordingly (keeping the aspect ratio) and place it to the center. Is there any way to do that?

Michael Pliskin
  • 2,352
  • 4
  • 26
  • 42

1 Answers1

29

First of all, overlay and background do not need to be the same size for composite to work. For example, given these two images:

sydney.png (352x288):

sydney

jet2.png (128x129):

jet2

Try the following commands:

convert -size 352x288 -composite sydney.png jet2.png -geometry 64x64+176+144 -depth 8 test.png

convert -size 352x288 -composite sydney.png jet2.png -geometry 32x32+176+144 -depth 8 test.png
  • -size specifies the output image dimensions
  • -geometry specifies the dimensions and location of the foreground

This is what I get for the first command:

result

EDIT

Here's a bash script to do it all for you in one line:

#!/bin/bash
if [ -z "$3" ]
then
    echo "usage: $0 background.png foreground.png output.png"
    exit 1
fi
bg_size=`identify -format '%wx%h' "$1"`
convert -size $bg_size -composite "$1" "$2" -geometry $bg_size+0+0 -depth 8 "$3"
mpenkov
  • 21,621
  • 10
  • 84
  • 126
  • So specify the same sizes to the `-size` and `-geometry` switches. For example: `convert -size 352x288 -composite sydney.png jet2.png -geometry 352x288+0+0 -depth 8 test.png` will stretch the airplane to fit into the image window. – mpenkov Jan 26 '11 at 12:53
  • Well - this could work but I don't know the sizes of the image in advance so it would be nice if it could auto-stretch or whatever. – Michael Pliskin Jan 26 '11 at 13:19
  • You can find the size of the images using the following bash command: `size=`identify -format '%wx%h' filename.png` and then work that into a bash script. Imagemagick doesn't seem to have a `-autostretchorwhatever` switch, unfortunately. – mpenkov Jan 26 '11 at 13:31
  • Ok that's what I've just done - works beautifully, thanks a lot! – Michael Pliskin Jan 26 '11 at 13:33
  • 3
    You're welcome. I went ahead and wrote you a script anyway -- see my updated answer. – mpenkov Jan 26 '11 at 13:39
  • @misha Thanks - exactly what I figured out as well. Thanks a ton for the tips! – Michael Pliskin Jan 27 '11 at 15:25
  • u r a lifesaver.. I was getting crazy about how to achieve this. – holographix Apr 09 '15 at 12:12
  • I had to add the `-compose multiply` option to the command to get the desired blending result (IM version 6.9.5). – Brian Hawkins Nov 07 '16 at 18:24
  • It's great! But how do I place foreground to the CENTER? – cronfy Feb 18 '20 at 16:03