Text to Image in PHP with GD

This is simple script to demonstrate the capabilities of PHP with the GD library, which provides a lot of image functions that can be useful in many applications. GD provides a rich set of functions. For a complete list of these functions, check the PHP manual.

header('Content-Type: image/png');
// Text to be converted to image
$text = 'Hello World';
// Font to use, give accessible path from script
$font = './arial.ttf';
// Convert HTML entities into ISO-8859-1
$text = html_entity_decode($text,ENT_NOQUOTES, "ISO-8859-1");
// Create the image
$im = imagecreatetruecolor(160, 160);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
// Create some colors
imagefilledrectangle($im, 0, 0, 160, 80, $white);
// Add the text
imagettftext($im, 12, 0, 20, 20, $black, $font, $out);

GD can also be used to create and manipulate image files in a variety of different image formats, including GIF, PNG, JPEG, WBMP, and XPM.


  • Though GD supports Unicode text inputs, it doesn’t support complex text rendering
  • Complex Text Rendering is required for properly displaying many language texts, such as the Arabic alphabet and scripts of the Brahmic family, which includes Tamil and many other Indic scripts.

There is a alternative for this using Pango and Cairo in PHP. I’ll post a detailed update on that in my next post.

2 thoughts on “Text to Image in PHP with GD”

Leave a Reply