Search code examples
cropimage-resizingimagemagick-convert

How do I use Imagemagick's convert to scale once and then crop multiple areas and save each crop in a separate file?


I have a 4K image that I would like to resize to a 12K image (×3).

Then I want to crop the 12K image in 9 separate 4K images.

I know how to run the command to create one of these crops and repeat that command 9 times (with varying positions).

convert input.jpg -resize 11520x6480 \
                 -crop 3840x2160+0+0 \
        output-top-left.jpg

But the resizing takes close to forever so I was hoping I could resize once and then crop 9 times in one go. So... How do I crop all 9 areas in one go?


Solution

  • You can crop into 9 parts (3x3 array of images in Imagemagick using its tile cropping. See https://legacy.imagemagick.org/Usage/crop/#crop_tile

    convert input.jpg -resize 300% -crop "3x3@" output.jpg
    

    from which you will get output-0.jpg, output-1.jpg ... output-8.jpg

    If you want to crop different size regions, then you can do that as follows:

    convert input.jpg -resize 300% -write mpr:img \
    \( mpr:img -crop W1xH1+X1+Y1 +repage +write output-1.jpg \) \
    \( mpr:img -crop W2xH2+X2+Y2 +repage +write output-2.jpg \) \
    ...
    \( mpr:img -crop W9xH9+X9+Y9 +repage +write output-9.jpg \) \
    null:
    

    If on Windows remove the \ from ( ... ) and change the end of line \s to ^s

    If on Imagemagick 7 use magick in place of convert