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
 $im = ImageCreate(200,200);
 $white = ImageColorAllocate($im,0xFF,0xFF,0xFF);
 $black = ImageColorAllocate($im,0x00,0x00,0x00);
 ImageFilledRectangle($im,50,50,150,150,$black);
 ImageString($im,5,50,160,"A Black Box",$black);
 Header('Content-Type: image/png');
 ImagePNG($im);
?>

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 to use:

ImageString(image, font, x, y, text, color);

Fonts

Fonts in GD are identified by numbers. 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 $im = ImageCreate(200,200); $black = ImageColorAllocate($im,0x00,0x00,0x00); ImageString($im,1,10,10,"Font 1: ABCDEfghij",$black); ImageString($im,2,10,30,"Font 2: ABCDEfghij",$black); ImageString($im,3,10,50,"Font 3: ABCDEfghij",$black); ImageString($im,4,10,70,"Font 4: ABCDEfghij",$black); ImageString($im,5,10,90,"Font 5: ABCDEfghij",$black); Header('Content-Type: image/png'); ImagePNG($im); ...

Get Programming PHP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.