DekGenius.com
Previous Section  < Day Day Up >  Next Section

13.1 Graphics

Your PHP programs can produce more than just HTML web pages. With the GD extension, they can also dynamically generate graphics—for example, you can create custom buttons. Example 13-1 draws a rudimentary button whose text comes from the button URL variable.

Example 13-1. Drawing a button image
<?php

// GD's built-in fonts are numbered from 1 - 5
$font = 3;

// Calculate the appropriate image size
$image_height = intval(imageFontHeight($font) * 2);
$image_width = intval(strlen($_GET['button']) * imageFontWidth($font) * 1.3);

// Create the image
$image = imageCreate($image_width, $image_height);

// Create the colors to use in the image
// gray background
$back_color = imageColorAllocate($image, 216, 216, 216);
// blue text
$text_color = imageColorAllocate($image, 0,   0,   255);
// black border
$rect_color = imageColorAllocate($image, 0,   0,   0);

// Figure out where to draw the text
// (Centered horizontally and vertically 
$x = ($image_width - (imageFontWidth($font) * strlen($_GET['button']))) / 2;
$y = ($image_height - imageFontHeight($font)) / 2;

// Draw the text
imageString($image, $font, $x, $y, $_GET['button'], $text_color);
// Draw a black border
imageRectangle($image, 0, 0, imageSX($image) - 1, imageSY($image) - 1, $rect_color);

// Send the image to the browser
header('Content-Type: image/png');
imagePNG($image);
imageDestroy($image);
?>

If Example 13-1 is saved as button.php in the document root directory of your web server, then you can call it like this:

<img src="/button.php?button=Click+Here">

It then outputs a button that looks like Figure 13-1.

Figure 13-1. Dynamic button
figs/lphp_1301.gif


Read more about these functions in Chapter 9 of Programming PHP by Rasmus Lerdorf and Kevin Tatroe (O'Reilly), in Chapter 15 of PHP Cookbook by David Sklar and Adam Trachtenberg (O'Reilly), and in the Image section of the PHP Manual (http://www.php.net/image). Jeff Knight's presentation to NYPHP about PHP's image functions is also a good source of information. It's available at http://www.nyphp.org/content/presentations/GDintro.

    Previous Section  < Day Day Up >  Next Section