Autocrop images with imagemagick

Often one has to crop excess margins from an raster image. Common image graphical editors have autocrop tool, but if many files need to be processed, opening and saving files one by one quickly becomes tedious.

A better solution is to use convert tool that is a part of the powerful Imagemagick toolkit:

convert image.jpg -trim -bordercolor White -border 20x10 +repage cropped_image.jpg
This command reads the original file, removes (trims, crops) white borders, adds 20 pixel white borders horizontally and 10px vertically, and stores the file as cropped_image.jpg.

It is also possible to process all image files in the current directory with the following one line command:
for i in `ls *.jpg`; do convert $i -trim -bordercolor White -border 20x10 +repage cropped_`basename $i`; done

If you want to convert to another image format, it can be done conveniently at the same time (-quality option controls the jpg quality):
for i in `ls *.gif`; do convert $i -trim -bordercolor White -border 20x10 -quality 92 +repage cropped_`basename $i gif`jpg; done
Above basename utility is used for trimming suffix from the file name.

Advertisements

6 Responses to “Autocrop images with imagemagick”

  1. David A Says:

    You don’t need the backticks and ls in a for-loop

    for i in `ls *.jpg`; do

    can be changed to

    for i in *.jpg; do

    which is not only simpler but also better, safer, sexier, and less expensive. Well, it is at least simpler. And better.

  2. Isabel Says:

    Doing this for pdf images reduces awfully the quality, even when setting -quality 100. Any other suggestions for pdf autocropping?

    • kawakamasu Says:

      Imagemagick is not great when working with vector graphics such as pdf. You might like to try pdfcrop, available in most linux distributions. Usage: pdfcrop input.pdf output.pdf (see the documentation for more options).

  3. ziopera Says:

    thanks man, that was really useful

  4. Jeffrey Killeen Says:

    It seems ImageMagick 7 has a different syntax. Any guidance on correct syntax for autocrop would be very appreciated.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: