Read more

ImageMagick: How to auto-crop and/or resize an image into a box

Arne Hartherz
July 21, 2017Software engineer at makandra GmbH

Auto-cropping

ImageMagick can automatically crop surrounding transparent pixels from an image:

convert input.png -trim +repage output.png
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

You need to +repage to update the image's canvas, or applications will be randomly confused.
Trimming specific colors is also possible, see the documentation Show archive.org snapshot .

Resizing into a box

Occasionally, you want to resize an image to a maximum width or height, and change the "outer" image dimensions to something that won't match the input image.

To resize a none-square image "into" a square box, where the image is centered, say something like this:

convert input.png -resize '128x128>' -gravity center -background transparent -extent 128x128 output.png

This will not skew the image itself, and fill up with transparent pixels.
If input.png is smaller than 128x128, it will not be enlarged because of the > flag. The resulting image will be 128x128, and any smaller image will be centered.

Auto-cropping and resizing

Combine the above like so:

convert input.png -trim +repage -resize '128x128>' -gravity center -background transparent -extent 128x128 output.png
Posted by Arne Hartherz to makandra dev (2017-07-21 15:53)