Ben Dodson
Ben Dodson

Reputation: 13

Image Magick - Composite an image over another without automatic cropping

I am creating a script that will turn any image into a square by cropping an internal square of the original image and using that as a faded background for the original. Original Final Result

The ImageMagick commands I have work for the most part. However, it sometimes crops the original image when composing it over the background image. Original Final - You can see feet have been cropped

Here are the commands I am using in the script:

1. Add transparent bars to fit square:
convert reference -trim +repage -resize '500x500>' -gravity center -background transparent -extent 500x500 refMain.png

2.Internal Cropped Background Image:
convert reference.jpg \
          \( +clone +level-colors white \
             \( +clone -rotate 90 +level-colors black \) \
             -composite -bordercolor white -border 1 -trim +repage \) \
          +swap -compose Src -gravity center -composite \
          -thumbnail '500x500>' refBG.png

3.Fade Out Background Image:
convert refBG.png -fill white -colorize 50% refBG.png

4.Overlay thumbnail onto stretched background:
composite -gravity center refMain.png refBG.png final.png

I am wondering what I can add/change to the composite command (or to any of them) to ensure that the 'main' image is overlaid in it's entirety over the background, without being cropped.

Upvotes: 0

Views: 784

Answers (1)

GeeMack
GeeMack

Reputation: 5395

With ImageMagick you should be able to do your entire operation in a single command. Try something like this...

convert input.jpg -resize '500x500>' -write mpr:img0 \
   -set option:distort:viewport '%[fx:max(w,h)]x%[fx:max(w,h)]' \
   -distort SRT '%[fx:(w>h)*(w/2)],%[fx:(h>w)*(h/2)] %[fx:max(w/h,h/w)] 0' \
   -fill white -colorize 50 mpr:img0 -gravity center -composite output.png

(Edited the command to fix a syntax problem, and added some detail to my description below.)

That will take an input image of any dimensions and resize it to fit in a 500x500 viewport. Then it writes a copy of that to a memory register "mpr:img0" to use later in the command.

Next it sets a viewport for the upcoming distort operation. It will be square, the dimensions of the larger of width or height.

Then using "-distort" it scales the image to fit centered in the resized and squared viewport. Then it colorizes that with 50% white.

After that it brings the input image back with that memory register "mpr:img0", sets the gravity to center, composites the input over the squared, whitened background, and writes the output file.

I've tested this command with ImageMagick v6 in a bash shell, and in Windows with a couple syntax changes. It should work with IMv7 by changing "convert" to "magick", but could be streamlined a little more because IMv7 has a more extensive use of FX expressions.

Upvotes: 1

Related Questions