Creating Dynamic Text Images
PHP has the ability to create on-the-fly images with the use of GD. This tutorial will aid you in creating a dynamic image with a TrueType Font (TTF) string on it.
Firstly, you need to decide what font to use. For this tutorial, I’m going to use MS Comic Sans, just because it was readily available to me. You need this file somewhere available to your webserver–I have a /Fonts directory with all of mine.
The function imagettfbbox() will give you the coordinates of how large the text image will need to be; all you need to do is a little math to calculate width and height from these. Here is the line I am using to get the coordinates: $size = imagettfbbox(12,0,"Fonts/comic.ttf","image string");
Now we can create our image. Since we don’t need a whole lot of functionality with this image, I’m just going to use imagecreate(): $im = imagecreate(abs($size-$size),$size+abs($size));. Now that you’ve done that, go ahead and choose whatever colors you like. Remember that the first color you allocate will be the background color, and you will need a variable name for the foreground (text) color. I’ve simply chosen $black and $white (background).
Place your text on the image, and you’re almost done. The only thing you really need to know about how to do this is that the Y coordinate of the text is usually a bit off. To correct this, we just need the upper coordinate of the textbox, which is $size. Since this value can be negative, we need to take the absolute value by using abs(). Now we are ready to place the text on the image: imagettftext($im,12,0,0,abs($size),$black,"/Fonts/arial.ttf","image string");
Output and destroy, and you’re done! Choose your format to output to. I recommend the PNG format by using the command imagepng($im). To finish up, all you need to do is destroy your image to clear it from memory: imagedestroy($im);.