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.
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.
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 ...
Get Programming PHP 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.