Batch Crop Images using ImageMagick

One of the tasks I perform today is batch cropping a lot of pictures. I have found ImageMagick very useful to scales and crop the images. Mogrify is a command of the ImageMagick package and allows us to perform many operations on multiple images. I’ll post it here as a future reference for myself and perhaps it will help others as well.

Step 1: Install MacPorts:

https://www.macports.org/install.php

After the installation, if you got an error:

sudo: port: command not found

Part of the problem is that MacPorts binaries are installed in /opt/local/bin, so you will need to manually adapt your shell’s environment to work with MacPorts:

export PATH=$PATH:/opt/local/bin source .profile sudo port -v selfupdate

Step 2: Install ImageMagick

http://www.imagemagick.org/script/binary-releases.php

sudo port install ImageMagick

The port command downloads ImageMagick and many of its delegate libraries. If you got an error:

convert: command not found

Set the MAGICK_HOME environment variable to the path where you extracted the ImageMagick files.

export MAGICK_HOME=”$HOME/ImageMagick-6.9.1"

If the bin subdirectory of the extracted package is not already in your executable search path, add it to your PATH environment variable.

export PATH=”$MAGICK_HOME/bin:$PATH”

Set the DYLDLIBRARYPATH environment variable:

export DYLDLIBRARYPATH=”$MAGICK_HOME/lib/

Step 3: Add the missing decoding library

When trying to convert jpeg images, it came up with this error message:

“convert: no decode delegate for this image format “

  1. Go to: http://www.imagemagick.org/download/delegates/ and download the required/missing delegate library. For example jpegsr9a.zip.

  2. Unzip the file

  3. Change directory to the folder

    cd jpeg-9a

  4. And run

    ./configure make make test make -n install

Step 5: Usage

To avoid overrides the original image files, create a new folder, copy the images and backup in that folder.

For resize a single image to a height of 600px with the same aspect ratio, you could run this command:

convert input.png -geometry x600 output.png

If you prefer to covert all images of a folder, change directory to the folder and use

mogrify -geometry x600 .png*

To scale down an image to 200 pixels:

convert myPhoto.jpg -resize 200x200^

To crop the image from centre:

convert myPhoto.jpg -gravity Center -crop 200x200+0+0 +repage newPhoto.jpg

The -gravity south option states that I want the crop to start at the bottom of my image. The -chop 0x25 states that I want to cut 25 pixels from the height.

mogrify -gravity south -chop 0x135 .jpg*

To resize all images in current directory to 800 width (and height reduced proportionally):

mogrify -resize 800 .jpg*

To rotate the images 90 degrees:

mogrify -rotate 90 .

For more information:

http://www.imagemagick.org

Originally published at victorleungtw.com on July 18, 2015.