Creating Dynamic Images with PHP

by kalai 2008-04-30 19:01:46


Many people do not realize that PHP can be used to create non-HTML data. This is especially useful for creating images on the fly. It could be simple bar graphs that display data from a database, or even simpler, just a way to create graphic buttons on the fly.
When I am putting up a site quickly, I find that it is a waste of my time to sit and fiddle with an image editor to create nice-looking graphical buttons and menus. Instead I will pick a nice TTF font and use the following simple script which I usually call 'button.php3':
<?php
Header("Content-type: image/gif");
if(!isset($s)) $s=11;
$size = imagettfbbox($s,0,"/fonts/TIMES.TTF",$text);
$dx = abs($size[2]-$size[0]);
$dy = abs($size[5]-$size[3]);
$xpad=9;
$ypad=9;
$im = imagecreate($dx+$xpad,$dy+$ypad);
$blue = ImageColorAllocate($im, 0x2c,0x6D,0xAF);
$black = ImageColorAllocate($im, 0,0,0);
$white = ImageColorAllocate($im, 255,255,255);
ImageRectangle($im,0,0,$dx+$xpad-1,$dy+$ypad-1,$black);
ImageRectangle($im,0,0,$dx+$xpad,$dy+$ypad,$white);
ImageTTFText($im, $s, 0, (int)($xpad/2)+1, $dy+(int)($ypad/2), $black, "/fonts/TIMES.TTF", $text);
ImageTTFText($im, $s, 0, (int)($xpad/2), $dy+(int)($ypad/2)-1, $white, "/fonts/TIMES.TTF", $text);
ImageGif($im);
ImageDestroy($im);
?>
It is very important to realize that you cannot put any HTML tags in this file. There should also not be any spaces or blank lines before or after the <? and ?> tags. If you are getting a broken image using this script, chances are you have a stray carriage return somewhere outside the PHP tags.
The above script would be called with a tag like this from a page: <IMG SRC="button.php3?s=36&text=PHP+is+Cool"> ,You will get the text image with font size of 36.

The 's' argument sets the font size and the button auto-scales itself to match.
Here it is again with s=18,You will get the text image with font size of 18.

Tagged in:

1368
like
0
dislike
0
mail
flag

You must LOGIN to add comments