O'Reilly logo

Programming PHP, 3rd Edition by Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

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

Images with Text

Often it is necessary to add text to images. GD has built-in fonts for this purpose. Example 9-5 adds some text to our black square image.

Example 9-5. Adding text to an image
<?php
$image = imagecreate(200, 200);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);

imagefilledrectangle($image, 50, 50, 150, 150, $black);
imagestring($image, 5, 50, 160, "A Black Box", $black);

header("Content-Type: image/png");
imagepng($image);

Figure 9-3 shows the output of Example 9-5.

The black box image with added text
Figure 9-3. The black box image with added text

The imagestring() function adds text to an image. Specify the top-left point of the text, as well as the color and the font (by GD font identifier) to use:

imagestring(image, font_id, x, y, text, color);

Fonts

GD identifies fonts by an ID. Five fonts are built-in, and you can load additional fonts through the imageloadfont() function. The five built-in fonts are shown in Figure 9-4.

Native GD fonts
Figure 9-4. Native GD fonts

The code used to show you these fonts follows:

<?php
$image = imagecreate(200, 200);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);

imagestring($image, 1, 10, 10, "Font 1: ABCDEfghij", $black);
imagestring($image, 2, 10, 30, "Font 2: ABCDEfghij" ...

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