Imagemagick – Tips and Tricks No. 1

Imagemagick (IM) is brilliant! If you want to do something to an image, Imagemagick can do it! Works on Linux and Windows. Can be scripted. Just use Imagemagick for your image manipulation needs.

Advert over. This and subsequent posts will serve as a reference for me, but also to show what imagemagick can do. Other than one liners, there will likely also be some bash scripting. I have also littered these posts with links to the IM documentation for all the features available with each of the actions.

I will use a reference image throughout, an MG Midget with a couple of people standing by it: mg.jpg. This is a jpg image, with dimensions of 1024 x 683, file size of 519kb

1. Resize an image
convert mg.jpg -resize 500 mg.jpg
This resizes the image to 500×333, (maintaining the aspect ratio)

2. Crop an Image
convert mg.jpg -crop 150x125+350+350 +repage mgcrop.jpg
You need to specify the output size (150×125) plus the start position for x & y on the original photo (+350+350). It may take some trial and error to find the exact spot! The +repage setting removed the virtual canvas (blank space left of original image after cropping).

To help things you can use a couple of IM tricks: gravity and percentage.
convert mg.jpg -gravity Center -crop 150x125+0+0 +repage mgcropgravity.jpg
convert mg.jpg -gravity Center -crop 50%x+0+0 +repage mgcropgravity50percent.jpg

3. Add Borders to an Image

I have used white borders so they show in the blog but you can use any colour your like:

convert mg.jpg -bordercolor white -border 20x20 -resize 250x mg borderx20resizex250.jpg


You can also use a percentage for borders:

convert mg.jpg -resize 250x -bordercolor white -border 20%x20% mgborderx20percentresizex250.jpg
convert mg.jpg -resize 250x -gravity center -background white -extent 120%x120% mgborderx20percent.jpg


4. Make an Image Square, with a Border

convert -define jpeg:size=200x200 mg.jpg -thumbnail '100X100>' -gravity center -crop 120x120+0+0\! -background white -flatten mgsquare.jpg


5. Make Thumbnails

convert -define jpeg:size=200x200 mg.jpg -thumbnail 100x100^ -gravity center -extent 100x100 mgthumb.jpg


Leave a Reply

Your email address will not be published. Required fields are marked *