Write text to an image using TrueType fonts in PHP

May 17, 2014 | Last tested: May 2015 | 975 views | Comments

With the use of the function imagettftext(), True Type Fonts (.ttf) can be used when writing text to an image using PHP.

For example.

The name of the font used on this example is 1942 report, and it is downloaded for free from this website.

Generate an image and write text to it using a True Type Font.

//set the desired width and height
$width = 500;
$height = 200;

//create a new palette based image
$newImg = imagecreate($width,$height);

//set the image background color to black
$bgColor = imagecolorallocate($newImg, 0, 0, 0);

//set the font size - pixel size for (GD1) or point size for (GD2)
$fontSize = 20;

//set the text angle
$angle = 0;

//set the text
$text = "ConsistentCoder.com";

//set the x and y positions of the text
$xPosition = 20;
$yPosition = 30;

//set the font
$font = '1942.ttf';

//set the font color to red
$fontColor_red = imagecolorallocate($newImg, 255, 0, 0);

//write the text on the created image
imagettftext($newImg,$fontSize,$angle,$xPosition,$yPosition,$fontColor_red,$font,$text);

//output the image to a file
imagepng($newImg,"write-text-to-an-image-using-truetype-fonts-in-php.png");

//destroy an image
imagedestroy($newImg);

Result.

Please mouse over here to view the image.

 

To add a text shadow.

  1. Add this code.
    //set the font shadow to grey
    $fontColor_grey = imagecolorallocate($newImg, 128, 128, 128);
    
    //write the text shadow
    imagettftext($newImg,$fontSize,$angle,($xPosition+1),($yPosition+1),$fontColor_grey,$font,$text);
    Below this code.
    //set the font
    $font = '1942.ttf';

Result:

Please mouse over here to view the image.