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.
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.
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" ...
Get Programming PHP, 3rd 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.