Search code examples
imagemagickimagemagick-convert

Put image on top of other image, but resize to fit first


I have two pngs. One is of unknown size (but always square), the 2nd is 1024x1024 and mostly transparent. I want to put the 2nd on top of the first, but first scale it down to the size of the first.

E.g. image1.png is 100x100, overlay.png is 1024x1024. The resulting image size is 100x100 with the overlay scaled down to 100x100 and put on top of the source file.

So far I got this:

magick convert ~/Downloads/Test\ icon.png  res/drawable/icon.png -gravity center -composite  ~/result.png

But the resulting image is 1024x1024 and the original is tiny somewhere in the center.


Solution

  • This will read in both images, resize the second to fit within the dimensions of the first, then composite the second centered over the first.

    magick img1.png img2.png \
       -resize %[fx:u.w]x%[fx:u.h] -gravity center -composite output.png
    

    If used in Windows, that continued line backslash "\" should be changed to a caret "^". If used in a Windows BAT script, the single percent signs "%" need to be doubles "%%".

    EDITED TO ADD: The way that works is this... Two images are read into the command. The FX expressions "u.w" and "u.h" stand for the width and height of the first image. So to "-resize" first image to its own dimensions doesn't change it, of course. And the second gets resized to fit within the dimensions of the first.