ImageMagick crop command generator
Generate ImageMagick crop commands: crop at x,y, centre crop to a size, crop to an aspect ratio, slice into tiles, or auto-trim borders. Explains why you need +repage.
ImageMagick's -crop does four quite different jobs depending on how you call it, and it leaves behind a piece of hidden state — the virtual canvas — that causes most of the confusion people run into afterwards.
Crop a rectangle at a position
magick input.jpg -crop 400x400+100+50 +repage output.jpg
The geometry reads WIDTH x HEIGHT + X + Y, measured from the top-left corner. The origin is +0+0.
Centre crop to an exact size
A bare -crop is the wrong tool if the source might be smaller than the target — you would get an image smaller than requested. Scale to cover first, then trim:
magick input.jpg -resize '400x400^' -gravity center -extent 400x400 output.jpg
This always produces exactly 400×400, never distorts, and works on any input size. Change center to north to bias the crop towards the top — useful for portraits, where centre-cropping tends to cut off heads.
Crop to an aspect ratio
magick input.jpg -gravity center -crop 16:9 +repage output.jpg
ImageMagick 7 accepts a ratio directly and works out the largest matching rectangle. ImageMagick 6 does not support this syntax — on IM6, use the centre-crop recipe above with explicit pixel dimensions.
Slice one image into a grid of tiles
magick input.jpg -crop 400x400 +repage tile_%02d.jpg
With no +X+Y offset, -crop cuts the whole image into a grid. Your output filename must contain a counter such as %02d, or every tile overwrites the previous one. Inside a Windows .bat file that counter has to be written %%02d.
Auto-trim a uniform border
magick input.jpg -fuzz 8% -trim +repage output.jpg
-trim on its own almost never works on real photographs or scans, because the border is never a perfectly uniform colour. The -fuzz tolerance is what makes it usable — start around 5–10% and raise it until it catches.
Why you need +repage
Cropping does not really remove the surrounding area; it records an offset into a "virtual canvas" that remembers where the crop came from. Formats that store an offset — GIF and PNG — keep that information, so:
- Your cropped PNG may render with unexpected padding.
- A later
-compositeor-extentlands in the wrong place. identifyreports a page geometry that does not match the pixel dimensions.
+repage discards that offset. Add it after every crop unless you specifically need the canvas preserved.
Crop and resize in one pass
magick input.jpg -crop 1200x1200+200+100 +repage -resize 400x400 output.jpg
Order matters: operators run left to right, so this crops first and then scales the result.