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 money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
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)