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.
April 2, 2012 at 2:40
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.
April 17, 2013 at 23:04
Doing this for pdf images reduces awfully the quality, even when setting -quality 100. Any other suggestions for pdf autocropping?
April 18, 2013 at 23:41
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).April 25, 2013 at 23:41
Perfect! Thx!