Technology

The wonders of ImageMagick

Posted by Pixafy Team

ImageMagick is an extremely powerful tool that I use for a multitude of tasks ranging from resizing to image compositions.  ImageMagick is normally ran via the command line, but as you saw from Dan’s article, we use the exec() or shell_exec() function in our code to execute the necessary commands. Below you can find some example of ImageMagick commands in action.

Resizing images

The following command will resize the given image into the proportional width and height specified:

convert <image_source> -resize <width>x<height>  <resultant_image >

This is pretty much the barebones resize command as there are a bunch more options you can add to this command. As stated above, this command will create an image with a proportional width and height, meaning if you pass in 300×400, you may not get that as the width and height of the resultant image, but one with a proportional width and height. To force the resultant image to be an exact width and height, all we need to do is add an “!” to the command as seen below:

convert <image_source> -resize <width>x<height>!  <resultant_image >

One important thing to note is that

<image_source> can be both a local path (/path/to/image)

or an image on the web (http://imageurl.com)

Image padding

The following command will place the image in the center of a white background with a specified width and height:

convert<image_source> -gravity center –background white –extent <width>x<height> <resultant_image>

I like to use this in combination with the resize command above in order to add padding to images that are smaller than the width and height specified against a  given background color.

Image layering/composition

The following command will overlay and image over another image at a specified coordinate xy

composite –geometry xy <image_1>  <image_2> <resultant_image>

These are just some of the awesome things you can do with ImageMagick; you can learn more at the ImageMagick website.