How to Crop an Image with ImageMagick Convert?
Using the ImageMagick convert command to crop an image
to a specific size requires the -crop geometry option. This
powerful command-line utility allows you to define the exact width and
height of the output image, along with optional X and Y offsets to
pinpoint the exact area you want to extract. Whether you need a quick
center-crop or a precise slice from the top-left corner, mastering the
basic geometry syntax ensures fast and efficient image manipulation
directly from your terminal.
The Basic Syntax
The fundamental syntax for cropping an image with ImageMagick relies on specifying the target dimensions and the starting coordinates.
convert input.jpg -crop WidthxHeight+X+Y output.jpg- Width: The desired width of the cropped image in pixels.
- Height: The desired height of the cropped image in pixels.
- X (Horizontal Offset): The distance in pixels from the left edge to start the crop.
- Y (Vertical Offset): The distance in pixels from the top edge to start the crop.
Note: If you omit the
+X+Yoffsets (e.g.,convert input.jpg -crop 300x200 output.jpg), ImageMagick will tile the entire image into multiple 300x200 pixel segments. Always include offsets if you only want a single, specific cut.
Practical Examples
Here are the most common scenarios you will encounter when cropping images.
1. Cropping from a Specific Coordinate
To extract a 400x300 pixel area starting 50 pixels from the left and 100 pixels from the top, use the following command:
convert photo.png -crop 400x300+50+100 cropped_photo.png2. Cropping from the Center
Cropping from the exact center of an image is a frequent requirement
for creating thumbnails. By combining the -gravity option
with -crop, you can change the origin point from the
top-left corner to the center.
convert photo.png -gravity Center -crop 500x500+0+0 center_cropped.pngWhen using -gravity Center, setting the offsets to
+0+0 ensures the crop happens perfectly dead-center.
3. Using Different Gravity Anchors
The -gravity option supports various compass directions,
allowing you to crop relative to different edges of the image.
| Gravity Direction | Source Anchor Point |
|---|---|
NorthWest |
Top-Left corner (Default) |
North |
Top-Center edge |
NorthEast |
Top-Right corner |
East |
Right-Center edge |
South |
Bottom-Center edge |
West |
Left-Center edge |
For example, to crop a 300x300 square from the bottom-right corner of an image:
convert photo.png -gravity SouthEast -crop 300x300+0+0 bottom_right.pngHandling Image Canvas Reset
ImageMagick sometimes preserves the original image’s canvas size
metadata (virtual canvas) after a crop, which can cause unexpected
layout behavior in certain viewers or web browsers. To completely
discard the original canvas data and set the new image boundaries as the
absolute layout, append the +repage option immediately
after the crop command:
convert photo.jpg -crop 600x400+10+20 +repage final_output.jpg