How to Crop an Image by X and Y Coordinates in ImageMagick?

The convert command in ImageMagick allows you to crop an image starting from precise X and Y coordinates by using the -crop geometry argument. By defining the target width and height along with the specific horizontal (X) and vertical (Y) offsets, you can instantly extract a specific region of any image. This article provides a straightforward guide on how to structure the command syntax, understand the geometry arguments, and handle edge cases like canvas resetting.

The Basic Command Syntax

To crop an image starting from a specific coordinate, ImageMagick uses a geometry string formatted as widthxheight+x+y.

The basic template for the command is:

magick convert input.jpg -crop WxH+X+Y output.jpg

(Note: In ImageMagick v7 and later, the modern command is simply magick, though magick convert or convert remains widely compatible).

Breaking Down the Components

Practical Examples

Example 1: Standard Crop

Suppose you have an image named photo.png. You want to cut out a section that is 400 pixels wide and 300 pixels high, starting exactly 150 pixels from the left (X=150) and 50 pixels from the top (Y=50).

magick convert photo.png -crop 400x300+150+50 cropped_photo.png

Example 2: Cropping to the Remaining Edge

If you want to start at a specific coordinate and keep everything to the right and bottom edges of the image, you can omit the width and height values while keeping the plus signs. ImageMagick will automatically extend the crop to the boundaries of the original image.

magick convert photo.png -crop +150+50 cropped_photo.png

Important Note on Canvas Resetting (+repage)

When you crop an image format that supports virtual canvases (such as PNG or GIF), ImageMagick retains the metadata of the original image size and the offset coordinates. This can cause the cropped image to appear with strange margins or incorrect positioning in web browsers or certain image viewers.

To completely discard the original canvas metadata and reset the image boundaries to match the new cropped size, append the +repage option immediately after the crop command:

magick convert photo.png -crop 400x300+150+50 +repage cropped_photo.png