Search code examples
mergeimagemagickcropimagemagick-convert

Crop and merge 3 images in single ImageMagick or Convert command


want to crop 3 regions from picture.jpg and join those 3 images in a single one.

Does it possible to crop and merge those 3 images in a single imagemagick or convert command? If not possible in a single command how would be the way to merge the 3 images in separate commands?

My goal is to avoid save temporal images doing it in a single command.

I get each region with the following commands.

convert picture.jpg -crop 212x32+717+190 -resize 318x48! out1.jpg
convert picture.jpg -crop 440x231+20+251 -resize 660x347! out2.jpg
convert picture.jpg -crop 440x231+490+251 -resize 660x347! out3.jpg
  • The size of output image I want to obtain would be 1336x411 pixels.
  • The position of each cropped image within final output image would be:

    out1.jpg located in (x,y) = (509,0) out2.jpg located in (x,y) = (0,64) out3.jpg located in (x,y) = (676,64)

picture.jpg picture.jpg

output.jpg output.jpg


Solution

  • Using IM's "convert" you can read in the original image, then "-clone" it several times within parentheses to work on copies of the input image. Inside the parentheses you can "-crop" each copy the way you want, and "-repage" them so each contains the finished canvas size and location information. After that you can "-delete" the original input, "-flatten" the three remaining images onto a single canvas, and write the output.

    The command would look like this at a Windows command prompt.

    convert input.jpg ^
       ( -clone 0 -crop 212x32+717+190 -resize 318x48! -repage 1336x411+509+0 ) ^
       ( -clone 0 -crop 440x231+20+251 -resize 660x347! -repage 1336x411+0+64 ) ^
       ( -clone 0 -crop 440x231+490+251 -resize 660x347! -repage 1336x411+676+64 ) ^
       -delete 0 -flatten output.png
    

    If you're running on a *nix system you'll need to replace those continued line carets "^" with backslashes "\", and also escape the parentheses with backslashes "\( ... \)".