O'Reilly logo

PHP Cookbook by Adam Trachtenberg, David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.4. Drawing Text

Problem

You want to draw text as a graphic. This allows you to make dynamic buttons or hit counters.

Solution

For built-in GD fonts, use ImageString( ):

ImageString($image, 1, $x, $y, 'I love PHP Cookbook', $text_color);

For TrueType fonts, use ImageTTFText( ):

ImageTTFText($image, $size, 0, $x, $y, $text_color, '/path/to/font.ttf', 
             'I love PHP Cookbook');

For PostScript Type 1 fonts, use ImagePSLoadFont( ) and ImagePSText( ):

$font = ImagePSLoadFont('/path/to/font.pfb');
ImagePSText($image, 'I love PHP Cookbook', $font, $size, 
            $text_color, $background_color, $x, $y);

Discussion

Call ImageString( ) to place text onto the canvas. Like other GD drawing functions, ImageString( ) needs many inputs: the image to draw on, the font number, the x and y coordinates of the upper right position of the first characters, the text string to display, and finally, the color to use to draw the string.

With ImageString( ), there are five possible font choices, from 1 to 5. Font number 1 is the smallest, while font 5 is the largest, as shown in Figure 15-5. Anything above or below that range generates a size equivalent to the closest legal number.

Built-in GD font sizes

Figure 15-5. Built-in GD font sizes

To draw text vertically instead of horizontally, use the function ImageStringUp( ) instead. Figure 15-6 shows the output.

ImageStringUp($image, 1, $x, $y, 'I love PHP Cookbook', $text_color);

Figure 15-6. Vertical ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required