Search code examples
imagemagickimagemagick-convertimage-masking

Imagemagick masking image and fitting space via resizing


INTRODUCTION

Let's say I have this image:

enter image description here

To the image I apply the mask in https://image.ibb.co/c5Nw6c/Mask.png (it's white, that's why I set it here). The mask is basically a message bubble with an arrow in the bottom right part.

The command (in bash) is the following:

size=`convert Mask.png -format "%wx%h" info:`
convert \( couple.jpg  -channel rgba -alpha on -resize $size \) Mask.png -compose copy_opacity -composite -compose over -background transparent -flatten png:result.png

And the result is:

enter image description here

PROBLEM

Let's now check the next two images:

Image 2

enter image description here

Image 3

enter image description here

If we do the same with these two, we will obtain the following results:

enter image description here

enter image description here

What we see here is that in order for the mask to be applied correctly, the proportions must be similar, otherwise, depending on the original image's size, it might cropped in the bottom, or in the right.

QUESTION

How can I avoid the cropping problem and:

  1. Make the trimmed image (with respect to the mask) fill the whole mask without leaving any gaps and without losing proportions? I guess, by resizing, but how?
  2. Let the resized photo be centered (center of gravity) with respect to the mask?

Thank you very much for your answers.


Solution

  • This command should take any input image then scale it to fill the mask. Next it composites the image centered over the mask with "srcin" to show just the part of the image where the mask is white. It finishes by flattening onto a white background. The output will be the dimensions of the mask.

    convert Mask.png image.jpg \
       +distort SRT "0,0 %[fx:t?max(u.w/v.w,u.h/v.h):1] 0 0,0" \
       -shave 1x1 +repage -gravity center -compose srcin -composite \
       -compose over -background white -flatten result.png
    

    This should work with IM 6.8.9 through IM 6.9.9.