PHP Graphics
Drawing Text
Problem
You want to draw text as a graphic. This allows you to make dynamic buttons or hit counters.
Solution
For built-in GD fonts, use ImageString():
ImageString($image, 1, $x, $y, 'I love PHP Cookbook', $text_color);
For TrueType fonts, use ImageFTText():
ImageFTText($image, $size, 0, $x, $y, $text_color, '/path/to/font.ttf',
'I love PHP Cookbook');
Discussion
Call ImageString() to place text onto the canvas. Like other GD drawing functions, ImageString() needs many inputs: the image to draw on, the font number, the x and y coordinates of the upper-right position of the first characters, the text string to display, and finally, the color to use to draw the string.
With ImageString(), there are five possible font choices, from 1 to 5. Font number 1 is the smallest, and font 5 is the largest, as shown in Figure. Anything above or below that range generates a size equivalent to the closest legal number.
Figure Built-in GD font sizes
To draw text vertically instead of horizontally, use the function ImageStringUp() instead. Shows the output:
ImageStringUp($image, 1, $x, $y, 'I love PHP Cookbook', $text_color);
Figure Vertical text
To use TrueType fonts, you must also install the FreeType library and configure PHP during installation to use FreeType. To enable FreeType 2.x, use --with-freetype-dir=DIR.
Like ImageString(), ImageFTText() prints a string to a canvas, but it takes slightly different options and needs them in a different order:
$image = ImageCreateTrueColor(200, 50);
ImageFilledRectangle($image, 0, 0, 199, 49, 0xFFFFFF); // white
$size = 20;
$angle = 0;
$x = 20;
$y = 35;
$text_color = 0x000000; // black
$text = 'Hello PHP!';
$fontpath = __DIR__ . '/stocky/stocky.ttf';
ImageFTText($image, $size, $angle, $x, $y, $text_color, $fontpath,
$text);
header('Content-type: image/png');
ImagePNG($image);
The $size argument is the font size in pixels; $angle is an angle of rotation, in degrees going counterclockwise; and /path/to/font.ttf is the pathname to the TrueType font file. Unlike ImageString(), ($x,$y) are the lower-left coordinates of the baseline for the first character. (The baseline is where the bottom of most characters sit. Characters such as “g” and “j” extend below the baseline; “a” and “z” sit on the baseline.)
Put them together, and you get Figure.
Figure TrueType text
No comments:
Post a Comment