HOWTO: Dynamic Image Generation with PHP

I came across a little issue lately. I wanted to be able to generate images, dynamically. I needed it to be done with PHP, and I needed it to be able to accept differing data (hence dynamic).

Where to turn? I had no way of automatically drawing an image with Fireworks, and certainly not from a Linux command line. You can automatically draw images with Fireworks and the other image generation applications, like MS Paint, you would need to program the mouse moves and clicks and so forth, but it CAN be done.

I don’t have a GUI available for this project. It’s all either command line based, or done by the programming languages available.

The solution for this is rather simple, PHP has a module available, PHP GD, and PHP is a very flexible programming language, so much so that you could take a white square and draw a rainbow on it if you had the time – some of us don’t.

For those interested, to generate an image with PHP is easy:


< ?php //Set content type to "gif" image. header("Content-type: image/gif"); //Specify text to be used on image $text = 'My Text String Here'; //or $_GET, $_POST - whatever floats. //Specify image to be used. $imagefile = "images/myimage.gif"; //Creates a PHP image from the original image $image = imagecreatefromgif($imagefile); //Defines RGB values for the color used. $red = 255; //value of red color $green = 0; //value of green color $blue = 127; //value of blue color //Allocates the color to the image $fontcolor = imagecolorallocate($image, $red, $green, $blue); //This defines the location to start writing the text. //The formula is the width of the image, minus 9, times the length of the text string, divide by two. $start = (imagesx($image) - 9 * strlen($provider)) / 2; //Adds the string to the image. Params are the image, the font, the pixel start, the text to be written and the color to write the string. imagestring($image, 18, $start, 29, $text, $fontcolor); //Generates a PNG of the image imagepng($image); //And then destroys the image to free memory. imagedestroy($image); //The image is sent back. You cannot change the content type with this, you simply send an image to the page. ?>

Pretty cool, heh? Amazing.

This entry was posted in Programming. Bookmark the permalink.

One Response to HOWTO: Dynamic Image Generation with PHP

Leave a Reply

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