While developing a site for a client, I needed to figure out a way to convert certain text elements into images. I had no clue how to do this but after doing a bit of research, I discovered a nifty library of functions already available through PHP. The GD library offers tons of cools way to dynamically create PNG, JPEG or GIF files and output them directly to your browser, but you need to make sure that your server has the library enabled.

You can check to see if the GD library available on your server by placing the code:

<?php phpinfo(); ?>

into a test.php file and uploading it to your site’s main directory. Open the file online and look to see if GD Support is Enabled. If it is, you are good to go.

The following code will dynamically create a PNG file from a text string.

header("Content-type: image/png");

$string = "This is my test string.";

$font  = 2;
$width  = imagefontwidth($font) * strlen($string);
$height = imagefontheight($font);

$image = imagecreatetruecolor ($width,$height);
$white = imagecolorallocate ($image,255,255,255);
$black = imagecolorallocate ($image,0,0,0);

imagestring ($image,$font,0,0,$string,$black);

imagepng ($image);

The above code must be included in its own file, it cannot be added to an existing PHP file with other functions. To access this image from another file just include it as the source in an image tag.

Test out turning text into an image by typing in something below.