15.7. Building Dynamic Images15.7.1. ProblemYou want to create an image based on a existing image template and dynamic data (typically text). For instance, you want to create a hit counter. 15.7.2. SolutionLoad the template image, find the correct position to properly center your text, add the text to the canvas, and send the image to the browser:
15.7.3. DiscussionBuilding dynamic images with GD is easy; all you need to do is combine a few recipes together. At the top of the code in the Solution, we load in an image from a stock template button; it acts as the background on which we overlay the text. We define the text to come directly from the query string. Alternatively, we can pull the string from a database (in the case of access counters) or a remote server (stock quotes or weather report icons). After that, we continue with the other settings: loading a font and specifying its size, color, and background color. Before printing the text, however, we need to compute its position; pc_ImagePSCenter( ) from Recipe 15.7 nicely solves this task. Last, we serve the image, and deallocate the font and image from memory. For example, the following code generates a page of HTML and image tags using dynamic buttons, as shown in Figure 15-9:
![]() Figure 15-9. Sample button pageIn this script, if a value is passed in for $_GET['button'], we generate a button and send out the PNG. If $_GET['button'] isn't set, we print a basic HTML page with two embedded calls back to the script with requests for button images — one for a Previous button and one for a Next button. A more general solution is to create a separate button.php page that returns only graphics and set the image source to point at that page. 15.7.4. See AlsoRecipe 15.6 for more on drawing text; Recipe 15.7 for more on centering text; an excellent discussion on dynamic image caching in Chapter 9, "Graphics," of Programming PHP, by Kevin Tatroe and Rasmus Lerdorf (O'Reilly).
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|