Write text to an image using TrueType fonts in PHP

May 17, 2014 | Last tested: May 2015 | 2610 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

//output the image to a file

//destroy an image


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
    Below this code.
    //set the font
    $font = '1942.ttf';


Please mouse over here to view the image.