Manipulating Images with PHP and GraphicsMagick

      7 Comments on Manipulating Images with PHP and GraphicsMagick

The Right Image

One of the things I like best about PHP is its support for a diverse array of tools and technologies. Take, for instance, image manipulation. Like most developers, I’ve known for a while that PHP comes with GD support for basic image generation and processing tasks, and I’ve even used it on occasion to dynamically create images from a base template. However, I recently needed to write some code involving cropping, resizing and otherwise torturing images and while researching the topic, I came across another PHP extension for image manipulation: the GraphicsMagick extension.

Based on the robust, multi-threaded GraphicsMagick library, aka the “Swiss Army knife of image processing”, PHP’s GraphicsMagick extension allows developers to add street cred to their image (sorry, I couldn’t resist!) with some fairly powerful API methods. This article discusses the extension in detail, introducing you to its key functions and showing you how to rotate, resample, transform, crop, carve, and otherwise mangle your images until they roll over and beg for mercy. So come on in, and bring your evil laughter with you!

Lights! Camera! Magic!

GraphicsMagick support in PHP comes through PECL’s ext/gmagick extension, which is maintained by Vito Chin and Mikko Koppanen, and provides an object-oriented API for image manipulation. Although this extension is currently in beta, it still allows you to do some fairly interesting things, including cropping, resizing and applying effects to images using PHP.

To get started with ext/gmagick, you’ll need to first make sure that you’re running PHP v5.1.3 or better, as the extension will not work on any earlier version. If you’ve got this, download the GraphicsMagick libraries (v1.2.6 or better) and compile them for your system. Assuming you’re on a *NIX system, here’s how:

Once this is done, you can proceed to install the GraphicsMagick extension using the pecl command, as shown below:

In case you don’t have access to the pecl command, you can also manually download the source code archive (v1.0.1-beta at this time) and compile it into a loadable PHP module with phpize:

Regardless of which procedure you choose, you should end up with a loadable PHP module named in your PHP extension directory. You should now enable the extension in the php.ini configuration file, restart your Web server, and check that the extension is enabled with a quick call to phpinfo():

This article uses GraphicsMagick v1.3.7 and ext/gmagick v1.0.1-beta.

Picture This

Once you have all the pieces loaded, let’s take ext/gmagick out for a quick spin. Here’s a simple example, which reads a photo and displays various photo properties:

Your primary access point to GraphicsMagick in PHP is through the Gmagick object, which is initialized in the first line of the script above. This object exposes a number of methods for image manipulation, but the one you’re going to be on first-name terms with very soon is the readImage() method, which accepts a file path as argument and reads the corresponding image into memory. Detailed information on the image, such as its dimensions, resolution, color depth and format, can now be obtained via a range of conveniently-named get*() methods, as illustrated above.

Here’s what the output looks like:

Scaling Up

If you need to dynamically resize images so they fit into a particular template, the GraphicsMagick extension has you covered: simply call the resizeImage() method with the new height and width. You can then send the new image to the output device, or write it to a file.

Consider the next example, which demonstrates by resizing an image to 150% of its original dimensions:

Here’s what the output looks like:

You can resample an image with the resampleImage() method, which accepts the dimensions of the new resolution, the image filter and the blur factor as arguments. Here’s an example of it in action:

And here’s some example output:

If what you’re really trying to do is create a thumbnail gallery, there’s a simpler way: the extension has a thumbnailImage() method, which accepts height and width numbers and generates a thumbnail version of the original image corresponding those dimensions. Here’s an example, which iterates over a directory, locates all the JPEGs in it and builds a thumbnail gallery of 150×150 images:

Here’s what the output looks like:

In the Frame

The GraphicsMagick extension also includes methods for rotating, flipping and cropping images. Here’s an example:

The rotateImage() method needs two arguments: the number of degrees by which to rotate the original image (second) and the fill color to use for any resultant empty space (first). Here’s what the script above generates:

You can create a vertical or horizontal mirror image with the flipImage() and flopImage() methods, respectively. Here’s an example:

And here’s an example of the resulting output:

You can crop a portion of the image with the cropImage() method, which accepts four arguments: the width and height of the area to crop, in pixels, and the X and Y coordinates of the pixel at the top left corner of the crop area. Here’s an example:

And here’s the resulting output:

Finally, you can magnify an image to twice its original size, or scale it down to half, with the magnifyImage() and minifyImage() methods, as below:

Take a look at what this produces:

Not My Type

Living up to its billing as the “Swiss Army knife of image processing”, the GraphicsMagick extension eats formats for breakfast. It can read and convert between most common image formats, including JPEG, GIF, PNG and TIFF, making it perfect for on-the-fly image conversion of uploaded photos or drawings. To convert an image, simply read it into memory with readImage(), use the setImageFormat() method to set the target format, and then write it back out with writeImage(). Simple, logical and oh so easy!

Here’s an example:

Incidentally, you can get a list of all the formats supported by your build with the queryFormats() method.

Border Incursion

You can add a 2D border to your image with the borderImage() method, which accepts three arguments: the border color, the border width and the border height. Here’s an example of it in action, generating a blue border that’s 4 pixels wide and 15 pixels high:

Here’s what the output looks like:

If you prefer 3D, the frameImage() method lets you apply a 3D border to your image. Here’s how it works:

And here’s an example of what the output looks like:

You can blur or sharpen an image with the blurImage() and sharpenImage() methods, both of which accept a blur/sharpen radius value and a standard deviation. Here’s an example:

And here’s the output:

Swirl Cycle

I’ve left the most impressive bits for last. The GraphicsMagick extension comes with a bunch of methods that allow you to apply special effects to your images. For example, the swirlImage() method adds a swirling effect to the center of your image:

Here’s an example of the resulting output:

The charcoalImage() method lets you re-render an image in the style of a charcoal drawing:

Here’s an example of the resulting output:

The oilPaintImage() method lets you render an image in the style of an oil painting:

Here’s an example of the resulting output:

The cycleColorMapImage() method lets you shift the colors of the image. As the manual suggests, if you do this a few times, it produces a psychedelic effect. Here’s an example:

And here’s an example of the resulting output:

The solarizeImage() method lets you apply a darkroom effect to your image:

The shearImage() method lets you move part of the image to create a “parallelogram effect”:

Here’s the output:

As the examples above illustrate, you no longer need a Photoshop expert to hold your hand when it comes to working with images, because PHP’s GraphicsMagick extension offers a full-fledged alternative for dynamic image manipulation. This article has only scratched the tip of the iceberg – the PHP manual documents more than 130 methods for this extension. In other words, there’s no shortage of things to play with – so why not try it out and see what you think!

Copyright Melonfire, 2009. All rights reserved.