Skip to Content
Programming PHP
book

Programming PHP

by Rasmus Lerdorf, Kevin Tatroe
March 2002
Intermediate to advanced
528 pages
21h 29m
English
O'Reilly Media, Inc.
Content preview from Programming PHP

Images with Text

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

Example 9-4. 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-2 shows the output of Example 9-4.

The image with text

Figure 9-2. The image with 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-3.

Native GD fonts

Figure 9-3. Native GD fonts

You can create your own fonts and load them into GD using the ImageLoadFont( ) function. However, these fonts are binary and architecture-dependent. Using TrueType fonts with the TrueType functions in GD provides much more flexibility.

TrueType Fonts

To use TrueType fonts with GD, PHP must have been compiled with TrueType support via the FreeType library. Check your phpinfo( ) page (as described earlier in this chapter) to see if your “GD” section ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming PHP, 3rd Edition

Programming PHP, 3rd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Programming PHP, 2nd Edition

Programming PHP, 2nd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Clean Code in PHP

Clean Code in PHP

Carsten Windler, Alexandre Daubois

Publisher Resources

ISBN: 1565926102Supplemental ContentCatalog PageErrata