1702330769

Now you can use any fonts you like on your web pages thanks to this recipe.


Although web browsers come with a reasonable range of default fonts, they don’t always provide the look you need for a particular web site. In such cases, you usually must resort to calling up a graphic editor and creating logos or headlines there. However, with this recipe all you have to do is upload the TrueType fonts you wish to use to your web site and you can then display text in these fonts by having the GD library convert it on the fly to GIF images. ## About the Recipe This recipe takes the name of a file to save as a finished GIF, the text and font to use in it, and various details such as color, size, and shadowing. It takes these arguments: + **$file**   The path/filename to save the image. + **$text**   The text to create. + **$font**   The path/filename of the TrueType font to use. + **$size**   The font size. + **$fore**   The foreground color in hexadecimal (such as “000000”). + **$back**   The background color (such as “FFFFFF”). + **$shadow**   The number of pixels to offset a shadow underneath the text (0 = no shadow). + **$shadowcolor**   The shadow color (such as “444444”). ## The code ```php function GifText($file, $text, $font, $size, $fore, $back, $shadow, $shadowcolor) { $bound = imagettfbbox($size, 0, $font, $text); $width = $bound[2] + $bound[0] + 6 + $shadow; $height = abs($bound[1]) + abs($bound[7]) + 5 + $shadow $image = imagecreatetruecolor($with, $height); $bgcol = GD_FN1($image, $back); $fgcol = GD_FN1($image, $fore); $shcol = GD_FN1($image, $shadowcolor); imagefilledrectangle($image, 0, 0, $width, $height, $bgcol); if($shadow > 0) imagettftext($image, $size, 0, $shadow + 2, abs($bound[5]) + $shadow + 2, $shcol, $font, $text); imagettftext($image, $size, 0, 2, abs($bound[5]) + 2, $fgcol, $font, $text); imagegif($image, $file); } function GD_FN1($image, $color) { return imagecolorallocate($image, hexdec(substr($color, 0, 2)) hexdec(substr($color, 2, 2)) hexdec(substr($color, 4, 2))); } ``` ## How to Use It To use this recipe, upload the TrueType file(s) you want to the same folder as the PHP program. In this case, it’s assumed you have uploaded a font called oldenglish.ttf. You can then create a GIF containing the text of your choice, like this: ``` GifText("greeting.gif", "Hello there!", "oldenglish.ttf", 26, "ff0000", 1, "444444"); ``` To display the image, you then only need to output some HTML code, like this: ``` echo "<img src='greeting.gif'>"; ``` However, to ensure the image is only created the first time it is needed, you will probably want to wrap the call to GifText() within an if statement, like this: ``` if(!file_exists("greeting.gif")) { GifText("greeting.gif", "Hello there!", "oldenglish.ttf", 26, "ff0000", 1, "444444"); } ```

(0) Comments