How to create images dynamically in PHP
Sometimes you may need to create images dynamically in your scripts, for example, if you want to create an image counter. Here is a very basic code fragment that creates a JPEG image and sends it to the browser:
$text = "eKstreme";
$pic=ImageCreate(60,30); //(width, height)
//colour1
$col1=ImageColorAllocate($pic,0,0,0);
//colour2
$col2=ImageColorAllocate($pic,255,255,255);//colour1
//Create a rectangle filled with colour2
ImageFilledRectangle($pic, 0, 0, 500, 30, $col2);
//Add the string to the image
ImageString($pic, 3, 5, 8, $text, $col1);
// Date in the past, so that the image is not cached by the browser
Header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
//tell the browser what it's about to recieve
Header("Content-type: image/jpeg");
//actually create the JPEG
ImageJPEG($pic);
//clean up!
ImageDestroy($pic);
Of course you can have fun with this script, or perhaps do something useful. If you set the $text variable to a counter variable that you increment using more code, then you can display an image counter. If so, you do not want the browser to cache the image (or everytime the page is visited, the counter is not incremented!), and so we set the 'Expires' header to sometime in the past.
PHP Graphics Ouput Demo
The picture below is the output of the above code:
View the code to see how the image is actually called in HTML.
