Using ImageMagick with PHP

On one of my sites, I needed to generate thumbnail images from various uploaded files. There are several options out there for doing that, including the GD and ImageMagick libraries. Since GD only supports a limited number of file types, the clear choice was to go with IM. ImageMagick itself does not have native PHP support. However, you can install Imagick, which is a PHP extension that allows you to use ImageMagick via PHP. Unfortunately, since all my sites are on a shared server, my hosting company will not install the Imagick extension. Which means I’m stuck using ImageMagick without the fancy tools Imagick provides.

But there is no need to fear, as working with ImageMagick through PHP is still pretty easy.

In PHP, you can run ImageMagick commands by using the exec() command. Here is an example:

// path to ImageMagick convert program
$convert = "/usr/bin/convert";

exec("$convert before.jpg after.png");

This example will convert the image file before.jpg to .png format and save it as after.png. Both images would be located in the same folder as the PHP file. However, you can use relative paths like this:

exec("$convert images/before.jpg images/after.png");



You can resize an image like this:

exec("$convert big.jpg -resize 200x200 small.jpg");

This will resize the image to a maximum dimension of 200 pixels. The image will maintain its same aspect ratio and proportions, just the largest dimension will become 200px.

Some great documentation and examples can be found here:

Leave a Reply

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