ImageMagick and PHP: Your Best Friend Or Your Worst Nightmare (Installing and a Few Examples)

| No TrackBacks
I recently dove head first into ImageMagick with PHP.  Ignoring the fact that ImageMagick's PHP documentation is lagging, and there are only a few solid real-world ImageMagick PHP examples out there, it's really not that bad!  This post is an attempt to officially document what I did to get ImageMagick working with PHP on CentOS 5.3.  I also wanted to share a real-world PHP-ImageMagick example from an actual project I built for a client.

1 - Installing ImageMagick for PHP

Initially, I tried to install imagick using "pecl install imagick", but that failed with this error:

Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to 
allocate 40 bytes) in /usr/local/lib/php/PEAR.php on line 766

According to this post on ActiveState, "...the pecl command intentionally ignores php.ini to avoid locking problems when upgrading PHP."  So, even if you change the memory limit config tunable in php.ini (like I initially tried), the pecl install is still going to fail.  So, the solution to this is to use pear instead.  I successfully installed imagick with "pear install pecl/imagick-2.2.1" as root.  From what I read online, there are some known issues with PHP 5.1.6 and imagic-2.2.2 (the latest stable version as of 5/1/09).  As a result, I installed one rev behind to avoid the linkage issue.

The pear install worked fine, and I saw the following post-install output on my root console:

Build process completed successfully
Installing '/var/tmp/pear-build-mark/.../usr/lib/php/modules/imagick.so'
install ok: channel://pecl.php.net/imagick-2.2.1
You should add "extension=imagick.so" to php.ini

The install process suggests that I should add "extension=imagic.so" to php.ini.  Well, on CentOS (and probably other distros), the module loading INI's were moved to /etc/php.d.  So, I had to create my own /etc/php.d/imagick.ini file to load imagick into PHP ...

; to load imagick (ImageMagick)
extension=imagick.so

To validate the install, I wrote a simple app in PHP to test ImageMagick with the PHP engine.  This test script draws a red 200x200px square with a large circle in it (as shown below) ...

<?php

$canvas = new Imagick();

$draw = new ImagickDraw();
$draw->circle(0,200,10,10);

$canvas->newImage(200,200,"#ff0000");
$canvas->drawImage($draw);
$canvas->setImageFormat('png');

header("Content-Type: image/png");
echo $canvas;

?>

test-circle.png

Yea!  Our ImageMagick install works with PHP; I can now build dynamic images on the fly programatically with PHP.


2 - The Problem

While building a new web-application for a client, I received a request to add a few custom headers to several columns in a table.  The headers, directly correspond to fields in a MySQL database table:

imagic-web-app-screenshot.jpg

To solve this problem, I had two options.

First, I could open up Photoshop and manually create these static header images myself, one-by-one.  Unfortunately, if I took that approach, and the client needs me to add or change a column name, I would have to go back into Photoshop and manually make the change.  I would also have to upload the new/modified image file, and tweak some source code to include the new or modified table header image.

The other preferred option is to use ImageMagick!  I solved this problem by writing a small PHP script that builds a dynamic PNG-image that contains the text I want on the fly.  No Photoshop, no FTP/SCP'ing files around, etc.  If I need to add or change the header name for a column in the table, it's literally a one-line code change.


3 - My Solution

Here's the PHP code I used to create a 100x14px PNG header image in the web-app (header images shown in the screen shot above):

<?php

$canvas = new Imagick();

$text = $_GET['t'];
if(empty($text)){
$text = "ERROR";
}

// Sanitize the input from a GET. Strip out any non-word
// characters and other junk. If it's not a word-character
// or a space, then remove it from the string.
$text = preg_replace("/[^\S ]/","",$text);

// Limit the size of the string to 20-chars.
$text = substr($text, 0, 20);

$draw = new ImagickDraw();

// I placed arial.ttf (TrueType Font file) in the same
// directory of the script. ImageMagick uses this file
// to annotate the image with text.
$draw->setFont("arial.ttf");
$draw->setFontSize(10);
$draw->annotation(0,10,$text);

$canvas->newImage(100,14,"#E1EFF9");

// Draw the image onto the canvas.
$canvas->drawImage($draw);

// Rotate the image
$canvas->rotateImage(new ImagickPixel(),"-90");

// I want a PNG
$canvas->setImageFormat('png');

header("Content-Type: image/png");
echo $canvas;

?>

If you need it, the Arial font file I used can be downloaded here.  To use this script, save it to a place on your server that executes .php scripts.  In your code that builds a chunk of dynamic HTML (or in a static HTML file), you can call this script using the <img> tag like so:

<img src="/path/to/script/image.php?t=i+love+kolich.com" />

You can change the t=... argument to whatever you want.  In this case, here's what this <img> would look like:

sample-show-me-some-love.png


Get 'er done.  Enjoy.

Did You Find this Helpful?

Did you find this post helpful, or at least, interesting?

  

Send Mark a Direct Message

If you'd like to send me a direct message, please do so below. However, I do not publicly post comments or messages submitted directly to me. So, if you're going to try to SPAM me, or my blog, you're pretty much wasting your time.

400 characters remaining

Error

About Mark

A Silicon Valley native, Mark Kolich is a full-time Software Engineer, a casual entrepreneur, and a consultant for hire. A web technologies expert, his current focus is on building powerful and robust cloud-driven web-applications using Java, PHP, Perl, AJAX, DHTML, CSS, and JavaScript. His favorite programming languages are PHP, Java and JavaScript. He uses Linux, enjoys biking to work, loves building great software, and always writes elegant, readable, and maintainable code.

No TrackBacks

No trackbacks attached to this entry.

Twitter (@markkolich)

Translate

About this Entry

This page contains a single entry by Mark Kolich published on May 1, 2009 6:25 PM.

5 Quick and Simple Tips to Better Secure your MySQL Server was the previous entry in this blog.

http://kolich.tel An Interesting Experiment: WHOIS crossed with DNS (.tel Domains and Network Solutions) is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.