///Creating Dynamic Text Images

Creating Dynamic Text Images

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[4]-$size[0]),$size[1]+abs($size[5]));. 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[5]. 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[5]),$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);.

2010-05-26T09:46:26+00:00 June 23rd, 2005|PHP|0 Comments

About the Author:

Brandon is a young web developer who puts emphasis in new web standards
and all the best practices.  Working mostly in open source projects of
his own, he has come to a great understanding with PHP, and helps others
to reach an understanding of their own.

Over the years as a web developer and software tinkerer, he has learned
new ways to overcome previously impossible tasks and still learns with
every large project.  He considers the web a constantly changing
environment, and has adapted to fit it.

Leave A Comment