[ Team LiB ] Previous Section Next Section

Working with Text

In this section we will work primarily with PHP's TrueType functions, which are useful for creating sophisticated charts or navigation. For a quick and easy way of writing to an image, however, the imagestring() function is the perfect tool.

Writing to an Image with the imagestring() Function

The imagestring() function is simple and useful. It requires an image resource, a font number, an x-axis location, and a y-axis location (with location 0,0 being the upper-left corner of the image). The function also requires the string you want to output and a color resource. Of these arguments, only the font numbers should need much explanation. These are built-in fonts of ascending size. Font 1 is the smallest in size, font 2 is slightly larger, and so on up to font 5. In the following fragment, we use imagestring() to write some text to an image:

header("Content-type: image/png");
$image = imagecreate( 200, 200 );
$red = imagecolorallocate($image, 255,0,0);
$blue = imagecolorallocate($image, 0,0,255 );

for ( $x=1; $x<=5; $x++ ) {
  imageString( $image, $x, (20*$x), (20*$x), "Welcome!", $blue );


We output a Content-type header and create an image and two color resources as before. Then we use a for loop to increment a counter variable, $x from 1 to 5. For each iteration of the loop, we call imagestring(), passing it our image resource, the font number held by the $x variable, and two location coordinates. We use the same string—Welcome!—and the color blue for each call to imagestring().

You can see the output from this fragment in Figure 15.8.

Figure 15.8. Writing text to an image with imagestring().


Working with TrueType Fonts

If you are working with the GD functions on a Windows system, you probably have access to the TrueType text functions already. If you are working in a Linux context, however, you might need to tell PHP about the TrueType library on your system when you compile it. We cover the installation process for a Linux system in Hour 2, "Installing PHP."

When you have TrueType support, you can use text functions to create image-based charts or navigation elements. PHP even gives you the tool you need to check that any text you write will fit within the space available.

Writing a String with imageTTFtext()

You can write text to your image with the imageTTFtext() function. This requires eight arguments: an image resource, a size argument representing the height of the characters to be written, an angle, the starting coordinates (one argument for the x-axis and another for the y-axis), a color resource, the path to a TrueType font, and the text you want to write.

The start point for any text you write determines where the baseline of the first character in the string will be.

Listing 15.8 writes a string to an image and outputs the result to the browser.

Listing 15.8 Writing a String with imageTTFtext()
 1: <?php
 2: header("Content-type: image/png");
 4: $image = imagecreate( 400, 200 );
 5: $red = imagecolorallocate($image, 255,0,0);
 6: $blue = imagecolorallocate($image, 0,0,255 );
 7: $font = "luxisri.ttf";
 9: imageTTFtext( $image, 50, 0, 20, 100, $blue, $font, "Welcome!");
11: imagepng($image);
12: ?>

We create a canvas with a width of 400 pixels and a height of 200 pixels on line 4. We define two colors (lines 5 and 6) and store the path to a TrueType font in a variable called $font (line 7).

Note that font files are likely to be stored in a different directory on your server. If you are not sure where, you could try searching for files with the .ttf extension. If you still cannot find the fonts you need on your system, you should be able to locate TrueType fonts on the Web and upload them to your Web space.

After we have stored the font path in the $font variable, we write the text Welcome! to the image on line 9.

For the call to imageTTFtext(), we define a size of 50, an angle of 0, a starting position of 20 on the x-axis, and a starting position of 100 on the y-axis. We also pass the function the color resource stored in the $blue variable, the font path stored in $font, and (finally) the text we want to output. You can see the result in Figure 15.9.

Figure 15.9. Writing text with imageTTFtext().


Of course, we have to guess where to put the text at the moment. The size argument does not give us an accurate idea of the text's height, and the width is a mystery. In fact, imageTTFtext() will return dimension information, but by then the deed is done. Luckily, PHP provides a function that enables you to try before you buy.

Testing Text Dimensions with imageTTFbox()

You can get information about the dimensions of text using the imageTTFbox() function, which is so called because it tells you about the text's bounding box. imageTTFbox() requires the font size, the angle, a path to a font file, and the text to be written. It is one of the few image functions that does not require an image resource. It returns an eight-element array, which is explained in Table 15.2.

Table 15.2. The Array Returned by imageTTFbox()




Bottom-left (horizontal axis)


Bottom-left (vertical axis)


Bottom-right (horizontal axis)


Bottom-right (vertical axis)


Upper-right (horizontal axis)


Upper-right (vertical axis)


Upper-left (horizontal axis)


Upper-left (vertical axis)

All figures on the vertical axis are relative to the text's baseline, which is 0. Figures for the vertical axis at the top of the text count down from this figure and are therefore usually minus numbers. Figures for the vertical axis at the bottom of the text count up from 0, giving the number of pixels the text drops from the baseline.

So, if you test a string containing a y with imageTTFbbox(), for example, the return array might have a figure of 3 for element 1 because the tail of the y drops 3 pixels below the baseline. It could have a figure of –10 for element 7 because the text is raised 10 pixels above the baseline.

To complicate matters, there seems to be a 2-pixel difference between the baseline as returned by imageTTFbbox() and the visible baseline when drawing text. You might need to adjust for this by thinking of the height of the baseline as 2 pixels greater than that returned by the imageTTFbbox().

On the horizontal axis, figures for imageTTFbbox() on the left take account of text that begins before the given start point by returning the offset as a minus number in elements 6 and 0. This is usually a small number, so whether you adjust alignment to take account of this depends on the level of accuracy you require.

You can use the information returned by imageTTFbbox() to align text within an image. Listing 15.9 creates a script that dynamically outputs text, centering it within our image on both the vertical and horizontal planes.

Listing 15.9 Aligning Text Within a Fixed Space Using imageTTFbbox()
 1: <?php
 2: header("Content-type: image/png");
 3: $height = 100;
 4: $width = 200;
 5: $fontsize = 50;
 6: if ( empty ( $_GET['text'] ) ) {
 7:   $text = "Change me!";
 8: } else {
 9:   $text = $_GET['text'];
10: }
11: $image = imagecreate( $width, $height );
12: $red = imagecolorallocate($image, 255,0,0);
13: $blue = imagecolorallocate($image, 0,0,255 );
14: $font = "luxisri.ttf";
15: $textwidth = $width;
16: $textheight;
17: while ( true ) {
18:   $box = imageTTFbbox( $fontsize, 0, $font, $text );
19:   $textwidth = abs( $box[2] );
20:   $textbodyheight = ( abs($box[7]) )-2;
21:   if ( $textwidth < $width - 20 )
22:     break;
23:   $fontsize--;
24: }
25: $pngXcenter = (int) ( $width/2 );
26: $pngYcenter = (int) ( $height/2 );
27: imageTTFtext( $image, $fontsize, 0,
28:     (int) ($pngXcenter-($textwidth/2)),
29:     (int) ($pngYcenter+(($textbodyheight)/2) ),
30:     $blue, $font, $text );
31: imagepng($image);
32: ?>

We store the height and width of the image in the variables $height and $width (lines 3 and 4) and set a default font size of 50 on line 5. On line 6, we test the built-in $_GET array for the presence of an element called 'text', setting a default on line 9 if it isn't present. In this way, the image can accept data from a Web page, either in the query string of an image URL or from form submission. We use imagecreate() on line 11 to acquire an image resource. We acquire color resources in the usual way and store the path to a TrueType font file in a variable called $font (lines 12–14).

We want to fit the string stored in $text into the available space, but we have no way of knowing yet whether it will. Within a while statement starting on line 17, we pass the font path and string to imageTTFbbox() on line 18, storing the resultant array in a variable called $box. The element $box[2] contains the position of the lower-right corner on the horizontal axis. We take this to be the width of the string and store it in $textwidth on line 21.

We want to center the text vertically, but only account for the area above the text's baseline. We can use the absolute value of $box[7] to find the height of the text above the baseline, although we need to adjust this by 2 pixels. We store this value in $textbodyheight on line 20.

Now that we have a working figure for the text's width, we can test it against the width of the image (less 10 pixels border). If the text is smaller than the width of the canvas we are using, we end the loop on line 22. Otherwise, we reduce the font size on line 23, ready to try again.

Dividing the $height and $width values by 2 (lines 25 and 26), we can find the approximate center point of the image. We write the text to the image on line 27, using the figures we have calculated for the image's center point in conjunction with the text's height and width to calculate the offset.

Finally, we write the image to the browser on line 31. Figure 15.10 shows the output from Listing 15.9.

Figure 15.10. Aligning text within a fixed space using imageTTFbbox().


This code can now be called from another page as part of an img element. The following fragment writes some simple code that enables a user to add his own string to be included in the image:

$text = ( empty( $_GET['text'] ) )?"Dynamic":$_GET['text'];
<form action="<?php print $_SERVER['PHP_SELF'] ?>" method="get">
<input type="text" name="text" />
<img src="listing15.9.php?text=<?php print urlencode($text) ?>" />

When we call the script in Listing 15.9 on line 10, we append a query string that includes the text to be added to the image. You can learn more about this technique for passing information from script to script in Hour 19, "Saving State with Cookies and Query Strings."

    [ Team LiB ] Previous Section Next Section