Image Processing with Imagine

Posted by on March 7, 2011
 

Image processing in PHP is a necessary evil but is needed more often than not in just about every web application.   With the various preferences in image processing libraries (think ImageMagick, GraphicsMagick and GD) it is difficult to find a library that provides a unified object oriented interface as well as implementing the general tasks in a simplistic fashion.

What is Imagine?

Imagine is an open source image manipulation library built with PHP 5.3 that implements an object oriented interface to ImageMagick, GraphicsMagick and GD.  It provides functionality for both common image manipulation and drawing tasks.  Instead of rewriting the same code to create a thumbnail, crop, rotate, resize, flip or even creating a composite image, Imagine provides a single line method to solve these tasks.

Getting Started

To get started, simply download and extract the library or take a checkout with Git.  Setup a simple autoloader through spl_autoload and start to make use of the library!

Setup of SPL Autoload

SPL autoload utilizing namespaces can be a bit tricky for those of you that have not done it yet.  However, once you set this up you will be happy that you do not need to worry about including all of the right files.

set_include_path('/path/to/lib/Imagine' . PATH_SEPARATOR . get_include_path());
function imagineLoader($class) {
    $path = $class;
    $path = str_replace('\\', DIRECTORY_SEPARATOR, $path) . '.php';
    if (file_exists($path)) {
        include $path;
    }
}
spl_autoload_register('\imagineLoader');

Our Example with Thumbnails

Thumbnails are a vital part of any application that is utilizing photos for both bandwidth purposes and to save the user the agony of having to load up large photos. They should generally always keep their proportions and Imagine makes this easier than pie.

$imagine = new \Imagine\Gd\Imagine();
$image = $imagine->open('example.png');
$thumbnail = $image->thumbnail(new Imagine\Image\Box(100, 100));
$thumbnail->save('example.thumb.png');

Now, that was easy!

Conclusion

Imagine is a great tool for speeding up your development when working with images. We only looked at a very basic example but take a look at the documentation to find far more complex examples.


About the author—Mike Willbanks is a software engineer manager at CaringBridge, a nonprofit providing free websites that connect people experiencing a significant health challenge to family and friends. He has more than a decade of experience programming with PHP and MySQL. He is a Zend Certified Engineer and focuses on high availability and high performance applications. Mike organizes the MNPHP and MN MySQL User Groups and has a passion for knowledge sharing and contributing back to the community.