Using Fonts and Printing Strings


Throughout this chapter, I have discussed using the GD extension to draw on the image canvas using a whole array of colors, styles, and brushes. However, I have yet to discuss how to go about the process of writing text (strings) to an image dynamically. Like most things involving the GD extension, PHP provides a wide range of options. As you will learn in this chapter, the GD extension supports the use of three font libraries (T1Lib, FreeType, and FreeType2), allowing you to work with both PostScript and TrueType fonts in your images. Beyond the font support provided by these libraries, the GD extension also provides five internal fonts. Because they are the least complex of the available options, I will begin the discussion here.

Using GD's Internal Fonts

Although the GD extension includes support for font libraries such as T1 and FreeType, internally the extension supports five fonts of different sizes that can serve many basic needs. Using these fonts is a fairly straightforward process encapsulated into a single GD function imagestring(). The syntax for this function follows:

 imagestring($img_r, $font, $start_x, $start_y, $string, $color); 

As you may expect, the $img_r and $color parameters are the standard image resource and color resource to use when drawing the text. The $font parameter is an integer defining the font to use (between 1 and 5), and $start_x/$start_y define the coordinates on the canvas where the text will be placed. Of course, the $string parameter represents the string to draw.

NOTE

Although $color is a standard GD color resource, special color constants such as IMG_COLOR_STYLED or IMG_COLOR_BRUSHED cannot be used in any text-related functions.


All things considered, using this function to draw text on the image canvas is as straightforward as it appears. To illustrate both how each internal GD font appears and the use of the imagestring() function, Listing 27.13 uses a for loop to generate an example of each font.

Listing 27.13. Using the imagestring() Function
 <?php     define("WIDTH", 300);     define("HEIGHT", 100);     $img = imagecreate(WIDTH, HEIGHT);     $white = imagecolorallocate($img, 255,255,255);     $black = imagecolorallocate($img, 0,0,0);     imagerectangle($img, 0, 0, WIDTH-1, HEIGHT-1, $black);     $start_x = 10;     $start_y = 10;     for($font_num = 1; $font_num <= 5; $font_num++) {         imagestring($img, $font_num, $start_x,                     $start_y, "Font #$font_num", $black);         $start_y += 15;     }     header("Content-type: image/png");     imagepng($img); ?> 

As you can see from the output image in Figure 27.13, each internal font is rendered differently from the next. Although this is acceptable for most simple-text applications, the GD extension expands on its internal font capabilities by allowing you to write text to a canvas vertically as well as horizontally. This is accomplished through the use of the imagestringup() function. This function is identical to imagestring() in terms of parameters; however, instead of drawing horizontally from the point defined by the $start_x and $start_y parameters, imagestringup() prints the text vertically.

Figure 27.13. Using the internal GD fonts.


NOTE

Certain topics relating to the internal font functions (such as imagestring()) have been omitted from this chapter. Some functions, such as imagechar(), serve no meaningful purpose, whereas other topics (such as custom bitmap fonts) extend beyond the scope of this book. For information regarding these topics, consult the PHP manual, which documents them clearly.


When you are working with internal GD fonts (or custom bitmap fonts), the GD extension also provides the means to determine the width and height of a given font through the imagefontwidth() and imagefontheight() functions. The syntax for these function is as follows:

 imagefontwidth($font); imagefontheight($font); 

$font is the font resource to retrieve the width and/or height for (in pixels).

Using TrueType Fonts

Now that you have been exposed to the internal support for fonts in the GD extension, it should be clearly understood that it has obvious limitations. Beyond the limited styles, internal GD fonts can be drawn only in two directions (horizontally and vertically) and are relatively small. For more demanding text needs in your images, the support of an external font library such as FreeType is required. The FreeType library (when combined with the GD extension) allows you to use any TrueType font quickly and easily.

With TrueType fonts (TTF), two functions provide the majority of functionality. The first of these two functions is imagettftext(), which is the TTF counterpart to the GD imagestring() function, and the second is imagettfbbox(), which provides the necessary information for placement of a given string on the canvas. Starting with imagettftext(), the syntax for this function is as follows:

 imagettftext($img_r, $size, $angle, $start_x,                     $start_y, $color, $fontfile, $string); 

As expected, $img_r, $start_x/$start_y, and $color indicate the image resource, drawing coordinates, and color to use when rendering the TTF string to the canvas. The $size and $angle parameters represent the size to render the font as well as the angle (in degrees) on which the string will be rendered to the canvas. The final two parameters, $fontfile and $string, represent the path and filename of the TTF to use and $string represents the text to draw onto the canvas.

Although this function requires a number of parameters, in practice it is quite simple to use. Listing 27.14 provides a simple script that uses a TrueType font to display a string in an image, and Figure 27.14 provides two outputs of the same script. The first of these outputs is with the F_ANGLE constant set to zero, and the second uses a value of 20 (signifying 20 degrees). Note that the font name myfont.ttf is just a placeholder; replace that with a font name of your liking that exists on your system.

Listing 27.14. Using the imagettftext() Function
 <?php     define("WIDTH", 300);     define("HEIGHT", 100);     define("F_SIZE", 40);     define("F_ANGLE", 0);     define("F_FONT", "myfont.ttf");     $img = imagecreate(WIDTH, HEIGHT);     $white = imagecolorallocate($img, 255,255,255);     $black = imagecolorallocate($img, 0,0,0);     $start_x = 10;     $start_y = (int)HEIGHT/2;     $text = "PHP Unleashed";     imagerectangle($img, 0,0,WIDTH-1,HEIGHT-1, $black);     imageTTFtext($img, F_SIZE, F_ANGLE, $start_x,                  $start_y, $black, F_FONT, $text);     header("Content-Type: image/png");     imagepng($img); ?> 

Figure 27.14. Using TrueType fonts in GD.


As you can see, the TrueType support in the GD extension provides a great deal more flexibility than that of the internal fonts provided by GD alone. However, with this flexibility comes a bit more difficulty. TrueType fonts can be drawn at angles (as shown in Figure 27.16), making calculations to determine the "center" of the text much more difficult. To simplify this task, the GD extension provides the imagettfbbox() function, which returns a bounding box for the given string under a specific set of circumstances. A bounding box is simply a polygon that defines the outer edges of the string in question. The syntax for the imagettfbox() is as follows:

 imagettfbbox($size, $angle, $fontfile, $string); 

Figure 27.16. Rendering PostScript Fonts in GD


$size and $angle represent the size and angle of the string using the TTF font specified by $fontfile. When executed, this function returns an array containing four coordinates representing the bounding box for that string. This data is returned in the form of an eight-element indexed array where the first two elements represent the X,Y coordinate for the first vertex, the second two represent the second vertex, and so on. With this information available, calculations can be made to position the font appropriately on the canvas regardless of the angle or the size of the font.

NOTE

The coordinates of the bounding box returned by imagettfbox() are relative to the text being drawn. As a result, working with these coordinates can be confusing; however, as you will see in the following example, after you are accustomed to this method, it can be quite useful.


To illustrate the use of the bounding box (as well as to give you a visual idea of exactly how it works) Listing 27.15 draws a string in a TrueType font at an angle and at its bounding box while always centering it on the canvas.

Listing 27.15. Using the imagettfbbox() Function
 <?php     define("WIDTH", 300);     define("HEIGHT", 100);     define("F_SIZE", 40);     define("F_ANGLE", 20);     define("F_FONT", "myfont.ttf");     define("F_TEXT", "PHP Unleashed");     $img = imagecreate(WIDTH, HEIGHT);     $white = imagecolorallocate($img, 255,255,255);     $black = imagecolorallocate($img, 0,0,0);     imagerectangle($img, 0,0,WIDTH-1,HEIGHT-1, $black);     $box = imagettfbbox(F_SIZE, F_ANGLE, F_FONT, F_TEXT);     $start_x = (WIDTH/2) - (int)(($box[0] + $box[2] + $box[4] + $box[6])/4);     $start_y = (HEIGHT/2) - (int)(($box[1] + $box[3] + $box[5] + $box[7])/4);     $polygon = array($box[0]+$start_x,                      $box[1]+$start_y,                      $box[2]+$start_x,                      $box[3]+$start_y,                      $box[4]+$start_x,                      $box[5]+$start_y,                      $box[6]+$start_x,                      $box[7]+$start_y);     imagepolygon($img, $polygon, 4, $black);     imageTTFtext($img, F_SIZE, F_ANGLE, $start_x,                  $start_y, $black, F_FONT, F_TEXT);     header("Content-Type: image/png");     imagepng($img); ?> 

Figure 27.15. Using TrueType bounding boxes.


Using Postscript Type 1

If you prefer not to work with the TrueType format, the GD extension along with the T1 library allows you to work with PostScript fonts on your canvases. In many ways, the same techniques that applied to TrueType fonts (bounding boxes, and so on) also apply to the PostScript font functions. However, unlike using the TrueType functions provided by GD, you must take additional steps to use PostScript fonts in your scripts. These steps can be summarized as follows:

1.

Load the PostScript font from the file system.

2.

Draw the desired text to the canvas.

3.

Free the Font resource.

These three steps are directly connected to three individual functions: specifically, the imagepsloadfont(), imagepstext(), and imagepsfreefont() functions. Starting with the imagepsloadfont() function, the syntax is as follows:

 imagepsloadfont($fontfile); 

$fontfile is the PostScript font to load. Upon execution, this function returns a resource representing the loaded font that is used when working the remainder of PostScript functions (just like imagecreate() returns a resource to an image).

After the font has been loaded, it can be used to draw text onto an image canvas. As you may have already realized, the function that accomplishes the task of drawing to the canvas is the imagepstext() function whose syntax is as follows:

 imagepstext($img_r, $string, $font, $size,                    $f_color, $b_color, $start_x,                    $start_y [, $spacing , $char_spacing ,                    $angle , $antialias]) 

As you can see, imagepstext() accepts a large number of parameters. The first two parameters, $img_r and $string, represent the image resource and the string to display, and $font and $size represent the font resource (from imagepsloadfont()) and the size to use when displaying the font. The next four parameters, $f_color, $b_color, $start_x, and $start_y, represent the color resources for the foreground and background and the drawing coordinates on the canvas, respectively.

NOTE

Unlike most functions in the GD extension (and for PHP in general, for that manner), the imagepstext() function must be passed either the first 8 parameters or all 12. Hence, although the indicated parameters are considered optional, they are all required if any are used.


The first two of the optional parameters, $spacing and $char_spacing, are sused to indicate the amount of whitespace that exists between words and individual characters of the string, respectively. These values may be either positive or negative and are added to the default value for the font in use. Furthermore, these values are not in terms of pixels, but rather in pointsone pixel equals 72 points. The next optional parameter, $angle, represents the angle on which the text will be drawn to the canvas (in degrees) and is a floating-point value. The last optional parameter in this very involved function, $antialias, determines the amount of colors to use in anti-aliasing when rendering the image and must be either 4 or 16 colors.

Now that I have explained that incredibly long list of possible parameters, it is time to put this knowledge to use in a real example. Listing 27.16 produces a result similar to that found in earlier TrueType examples, but using a PostScript font (again, a placeholder name is used: myfont.pfb):

Listing 27.16. Using the PostScript Functions in GD
 <?php     define("WIDTH", 300);     define("HEIGHT", 100);     define("F_SIZE", 40);     define("F_ANGLE", 0);     define("F_FONT", "myfont.pfb");     $img = imagecreate(WIDTH, HEIGHT);     $white = imagecolorallocate($img, 255,255,255);     $black = imagecolorallocate($img, 0,0,0);     $font = imagepsloadfont(F_FONT);     $start_x = 10;     $start_y = (int)HEIGHT/2;     $text = "PHP Unleashed";     imagerectangle($img, 0,0,WIDTH-1,HEIGHT-1, $black);     imagepstext($img, $text, $font, F_SIZE, $black,                 $white, $start_x, $start_y, 0, 0, F_ANGLE, 16);     imagepsfreefont($font);     header("Content-Type: image/png");     imagepng($img); ?> 

Now that you have the basic idea of how PostScript fonts work as they relate to the GD extension, let's take a look at the manipulations that can be done with them. As was the case with TrueType fonts, the PostScript family of functions also supports bounding boxes that assist you in placing your strings appropriately on the canvas. This function is called imagepsbbox() and has the following syntax:

 imagepsbbox($string, $font, $size                    [, $spacing, $char_spacing, $angle]); 

$string is the text to be displayed using the font and size specified by the $font and $size parameters. Like the imagepstext() function, the imagepsbbox() function accepts either a total of three or six parameters. The meaning of these parameters is also identical to their imagepsbbox() counterparts. Unlike its counterpart with TrueType fonts, the imagepsbbox() function does not return an array of coordinates relative to the text. Instead, it returns two sets of real coordinates on the canvas, representing the lower-left and upper-right corners of the bounding box where index zero represents the X coordinate of the lower left, index 1 represents the Y coordinate, and so on.

After the text has been drawn to the canvas, if the font is no longer needed, the font resource should be destroyed. As you can see, this has been done in Listing 27.18 using the imagepsfreefont() function. The syntax for this function is as follows:

 imagepsfreefont($font); 

$font is the PostScript font resource to free. Failure to free PostScript fonts can cause many problems in your scripts. It is extremely important that you free any fonts loaded in order to prevent problems with your scripts.

At this point you have been introduced to all the functionality you need for most applications in which PostScript fonts are to be used. However, there are a few additional functions to cover that may be useful to you. The first of these function is imagepsslantfont(). The syntax of this function is as follows:

 imagepsslantfont($font, $slant); 

$font is the PostScript font resource and $slant is a floating-point number indicating how much to "slant" the font. For most applications, this number is almost always less than 1 (anything greater than the value of 2 makes the text difficult to read). It is important to realize that when you're working with this function, the loaded font is modified in memory permanently. To display this font in its initial style, it must be reloaded.

NOTE

In previous versions of PHP, the GD extension provided the imagepscopyfont() function, which could duplicate a font in memory, allowing you to make a copy before modification. However, at the time of this writing, that function was not available because of instability found in the T1 library.


Another modification to a PostScript font is "extending" (stretching it) or "condensing" (squishing it). Both of these actions are accomplished using the imagepsextendfont() function, which has the following syntax:

 imagepsextendfont($font, $ratio); 

$font is the font resource to modify and $ratio is a floating-point value representing the amount to extend or condense the font. When $ratio is less than 1, the font will be compressed, whereas values greater than 1 will extend the font.

To conclude the discussion of the PostScript functions available to the GD extension, let's look at some code that pulls together the last few functions I've discussed. The code in Listing 27.17 condenses (using imagepsextendfont()) and slants (using imagepsslantfont()) the loaded font before drawing the text to the canvas:

Listing 27.17. Using imagepsextendfont() and imagepsslantfont()
 <?php     define("WIDTH", 300);     define("HEIGHT", 100);     define("F_SIZE", 40);     define("F_ANGLE", 0);     define("F_FONT", "./colle9.pfb");     $img = imagecreate(WIDTH, HEIGHT);     $white = imagecolorallocate($img, 255,255,255);     $black = imagecolorallocate($img, 0,0,0);     $font = imagepsloadfont(F_FONT);     $start_x = 10;     $start_y = (int)HEIGHT/2;     $text = "PHP Unleashed";     imagerectangle($img, 0,0,WIDTH-1,HEIGHT-1, $black);     imagepsextendfont($font, 0.4);     imagepsslantfont($font, 0.4);     imagepstext($img, $text, $font, F_SIZE, $black,                 $white, $start_x, $start_y, 0, 0, F_ANGLE, 16);     imagepsfreefont($font);     header("Content-Type: image/png");     imagepng($img); ?> 

Figure 27.17. Using PostScript fonts and styles in GD.




PHP 5 Unleashed
PHP 5 Unleashed
ISBN: 067232511X
EAN: 2147483647
Year: 2004
Pages: 257

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net