Skip to Content
Programming PHP
book

Programming PHP

by Rasmus Lerdorf, Kevin Tatroe
March 2002
Intermediate to advanced
528 pages
21h 29m
English
O'Reilly Media, Inc.
Content preview from Programming PHP

Dynamically Generated Buttons

A popular use for dynamically generated images is to create images for buttons on the fly. Normally, a blank button background image is used and text is overlaid on top of it, as shown in Example 9-7.

Example 9-7. Creating a dynamic button

<?php
 $font = 'times';
 if (!$size) $size = 12;
 $im = ImageCreateFromPNG('button.png');
 // calculate position of text
 $tsize = ImageTTFBBox($size,0,$font,$text);
 $dx = abs($tsize[2]-$tsize[0]);
 $dy = abs($tsize[5]-$tsize[3]);
 $x = ( ImageSx($im) - $dx ) / 2;
 $y = ( ImageSy($im) - $dy ) / 2 + $dy;
 // draw text
 $black = ImageColorAllocate($im,0,0,0);
 ImageTTFText($im, $size, 0, $x, $y, $black, $font, $text);
 header('Content-Type: image/png');
 ImagePNG($im);
?>

In this case, the blank button (button.png) looks as shown in Figure 9-6.

Blank button

Figure 9-6. Blank button

Note that if you are using GD 2.0.1, antialiased TrueType fonts work only if the background image is indexed. If you are having problems with your text looking terrible, load your background image into any image-editing tool and convert it from a true color image to one with an 8-bit indexed palette. Alternatively, upgrade from GD 2.0.1 to GD 2.0.2 or later.

The script in Example 9-7 can be called from a page like this:

<img src="button.php?text=PHP+Button">

This HTML generates the button shown in Figure 9-7.

Figure 9-7. Generated button

The + character in the URL ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming PHP, 3rd Edition

Programming PHP, 3rd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Programming PHP, 2nd Edition

Programming PHP, 2nd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Clean Code in PHP

Clean Code in PHP

Carsten Windler, Alexandre Daubois

Publisher Resources

ISBN: 1565926102Supplemental ContentCatalog PageErrata