Cover by Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required