Some of the best ways to use the image functions in PHP are with existing images. For example, you can write a script to dynamically create buttons by first loading a blank button image from your hard drive and overlaying text on top. Loading images is remarkably easy, as you might expect, and takes the form of a call to imagecreatefrom*(), where the * is "png", "jpeg", or various other formats. These functions take just one parameter, which is the file to load, and return an image resource for use as we've been doing already.
The first step to creating a customisable button script is to create a blank button using the art package of your choice. See for an example:
Adding text to this button is largely the same as our existing text code, with a few minor changes:
The $blue colour is no longer needed, and we will not be using imagecreate()
We need to centre the text in the middle of the button
The font size needs to come down a little in order to fit the button
The new function in that script is getimagesize(), which returns the width and height of the image specified in its parameter as an array, with elements 0 and 1 being the width and height respectively. In addition, element 2 is the type of the picture, and will be set to either IMAGETYPE_BMP, IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_PSD, IMAGETYPE_SWF, amongst other values. This element is particularly helpful when used with image_type_to_mime_type().
Running that script without any parameters generates the picture shown in Figure 21 , although you can send "text" and "size" if you want to play around. With this script in place, you can generate a whole toolbar of buttons for a website using this one script, simply by changing the "text" value you pass in. Of course, it is not very efficient to keep regenerating the same buttons each time a page is loaded, so if I were you I would save each generated picture as a file named after the text used - that way you can use file_exists() to attempt to load the existing picture and save the extra work.
With just a little work, we can even add a simple shadow to the text. To accomplish this effect, shown in , you need to allocate a new colour for the shadow (I used black), then call imagettftext() twice - once for the shadow, and again for the text itself. I offsetted the shadow by +1 on X and Y, and the text by -1 on X and Y, completing the effect. If you really want to get fancy, you can add a third call to imagettftext() that uses grey and has a slightly smaller offset, giving a smoother shadow effect.