Dynamically Generated Buttons

Creating images for buttons on the fly is one popular use for generating images (this was introduced in Chapter 1 as well). Typically, this involves compositing text over a preexisting background image, as shown in Example 9-8.

Example 9-8. Creating a dynamic button

<?php
$font = "times";
$size = isset($_GET['size']) ? $_GET['size'] : 12;
$text = isset($_GET['text']) ? $_GET['text'] : '';

$image = imagecreatefrompng("button.png");
$black = imagecolorallocate($image, 0, 0, 0);

if ($text) {
  // calculate position of text
  $tsize = imagettfbbox($size, 0, $font, $text);
  $dx = abs($tsize[2] - $tsize[0]);
  $dy = abs($tsize[5] - $tsize[3]);
  $x = (imagesx($image) - $dx ) / 2;
  $y = (imagesy($image) - $dy ) / 2 + $dy;

  // draw text
  imagettftext($image, $size, 0, $x, $y, $black, $font, $text);
}

header("Content-Type: image/png");
imagepng($image);

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

Blank button

Figure 9-7. Blank button

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

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

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

Button with generated text label

Figure 9-8. Button with generated text label

The + character in the URL is the encoded form of a space. Spaces are illegal in URLs and must be encoded. Use PHP’s urlencode() function ...

Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.