Cover by Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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" ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required