henry.jarske.net

Writings

PHP: Using fonts to draw dynamic text

Using a script to create automatically sized image messages with any TrueType font at any size can come in handy. You use it to create dynamic titles for pages, maybe even to troll a forum. Here's how to do it.

The special functions used in this example are available in the majority of servers. If you have trouble getting this to work, check this page at php.net for information about the GD library requirements.

To use this code, you need to save it to a new .php file, configure it and in most cases include the actual font file with it. Read on after the code for the details.

<?php
  // Configuration
  $font = "arial.ttf";
  $size = 28;
  $text = "Lorem ipsum dolor sit amet";

  // Send headers
  header("Content-type: image/gif");
  header("Expires: " . gmdate('D, d M Y H:i:s', time() + 3600) . " GMT");
  header("Content-disposition: inline; filename=text.gif");

  // Check for server capabilities, font availability and also calculate coordinates
  if (function_exists("imagecreate")
      && ($area = @imagettfbbox($size, 0, $font, $text)) !== false)
  {
    $textwidth = $area[2] - $area[0] + 2;
    $textheight = $area[1] - $area[7] + 2;
    $textx = 1;
    $texty = -$area[7];
    $ok = true;

    // Create a base image
    $image = imagecreate($textwidth, $textheight);
    $white = imagecolorallocate($image, 255, 255, 255);
    $black = imagecolorallocate($image, 0, 0, 0);
    imagecolortransparent($image, $white);

    // Draw the background and text
    imagefilledrectangle($image, 0, 0, $textwidth, $textheight, $white);
    imagettftext($image, $size, 0, $textx, $texty, $black, $font, $text);

    // Output the image
    imagegif($image);
    imagedestroy($image);
  }
  // Something's broke, output a one pixel image
  else
  {
    printf(
      "%c%c%c%c%c%c" .
      "%c%c%c%c%c%c%c" .
      "%c%c%c%c%c%c" .
      "%c%c%c%c%c%c%c%c" .
      "%c%c%c%c%c%c%c%c%c%c" .
      "%c%c%c%c%c" .
      "%c",
      71,73,70,56,57,97,
      1,0,1,0,128,255,0,
      192,192,192,0,0,0,
      33,249,4,1,0,0,0,0,
      44,0,0,0,0,1,0,1,0,0,
      2,2,68,1,0,
      59);
  }
?>

That bit of code creates some black text with a transparent background in a GIF format. Check the basic configuration at the first few lines before using it.

Whichever font you choose, chances are that you'll have to find the actual font file if you want the script to work. If you're running Windows, open Control Panel > Fonts and copy any TrueType font from there to wherever you saved your PHP script.

If you're wondering about the repeating '%c' and numbers at the end, that's the disaster plan. In case of a font error or missing image functions, that part creates a valid, 1 by 1 pixel GIF image from scratch.