I recently ran into the issue of wanting to use fonts that were on my local PC to build nice looking headers for this site. While doing the research to find out how difficult it would be to embed a font into the page for those who don't have it on their PCs, I remembered my encounters with GD while testing out an image validation script.

The image headings that you see at the top of each page were created dynamically using the GD libraries and PHP functions with the Brushstroke Plain true type font. Allow me to show you an example complete with code.

First, I set up a new file named heading.php. In that file are the following contents:

<?php

// Set the content-type
header("Content-type: image/gif");

$fontsize = ( @$_GET['size'] ? $_GET['size'] : 18 );
$maxwidth = ( @$_GET['maxwidth'] ? $_GET['maxwidth'] : 500 );
$color = ( @$_GET['color'] ? $_GET['color'] : 'navy' );

$font = 'brush.ttf';
$text = stripslashes(@$_GET['text']);

// Create the image
$width = $maxwidth * 2;
while (
$width > $maxwidth) {
 
$fontsize--;
 
$size = imagettfbbox($fontsize, 0, $font, $text);
 
$width = $size[2] + $size[0] + 8;
 
$height = abs($size[1]) + abs($size[7]);
}

$im = imagecreate($width, $height);
$colourBlack = imagecolorallocate($im, 255, 255, 255);
imagecolortransparent($im, $colourBlack);

// Create some colors
$colors = array(
 
'black' => imagecolorallocate($im, 0, 0, 0),
 
'white' => imagecolorallocate($im, 255, 255, 255),
 
'greyish' => imagecolorallocate($im, 191, 197, 191),
 
'navy' => imagecolorallocate($im, 33, 59, 141),
 
'mustard' => imagecolorallocate($im, 181, 187, 99),
);

// Add the text
imagefttext($im, $fontsize, 0, 0, abs($size[5]), $colors[$color], $font, $text);

// Using imagepng() results in clearer text compared with
imagegif($im);
imagedestroy($im);

?>

Next, I call the above script as an image in my page template files:

<img src="<?php print '/path/to/heading.php?size=18&maxwidth=550&text=' . stripslashes($title); ?>">

The resulting image comes out in the height and width specific to the font name and size that is specified in the GET request. You can see examples of this in every page header of 4minds.com. Enjoy!