Fonts in GD2, GD PART IV

One of many things, however commonly used, is the function to write text to images with GD. When doing so we're limited to GD2's 5 standard fonts, by default - what we'll do here is taking a closer look on how to get around this and how to use a font we see fit for the purpose. A standard case of writing text to an image would look like


<?php
$im 
imagecreatefrompng("baseImageURL"); //1
$fontcolor imagecolorallocate($im000); //2

imagestring($im51012"Hello world!"$fontcolor); //3

header("Content-type: image/png"); //4
imagepng($im); //5
?> 

This code above does:
  1. Create a blank 150x20 image
  2. Set intended fontcolor to black
  3. Type out the string on $im, with built-in font 5, from x-coord 10 and y-coord 12, appying text "Hello world!" in the color black
  4. Set document header to identify itself as a PNG-image
  5. Flush the image
However, when wanting to use different fonts then the built-in ones, we pretty much have two choices. We can use .ttf-fonts or we can go for .gdf-fonts. The biggest problem is usually to get your hands on the specific fontfile as sites/companies like to charge you for them. One good option is to use a small program made by Dave Wedwick to convert standard windows fonts into .gdf ditos. Just convert them and upload by ftp ^^

The application is mirrored on this site and can be downloaded by clicking here

Assuming we'll do steps 1,2,4,5 as above, the different methods would look like

TrueType font printed as:
array imagettftext ( resource $image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string $text )

<?
$font 
'arial.ttf';
imagettftext($im2001012$fontcolor$font"Hello world!");
?>

Plain loaded font (.gdf) as:

<?
$font 
imageloadfont("lib/testfont.gdf");
imagestring($im$font1012"Hello world!"$fontcolor);
?>

With above code you should be able to easily load and use a font that suits your need. Cheers ^^