Resize Images with ImageMagick from PHP

by Stephen Fluin 2009.06.12

There are a few ways to resize images on disk using PHP. The first is to use a library that will work on GD images in memory. The second is to use GD manually to resize images. The final way that I am going to discuss is to use ImageMagick command-line tools.

Using the ImageMagick tools has the benefit of being able to leverage an existing executable that sits on the filesystem. You can install ImageMagick with the following command:

sudo apt-get install imagemagick

Use of this tool will come with some inherent security risks, as we will be executing system commands. This means you need to make sure the string representing the file's location has been fully sanitized. Once it has been sanitized, you need only make two system calls to resize an image. You can provide either a destination size, or a ratio.

$command = "mogrify -resize 95% $location";
exec($command);

Using the mogrify command allows a quick and effective image resizing, with only a dependency on a single system command.


permalink