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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)