Turn Text into an Image using the PHP GD Library

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:

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);
imagefill($image,0,0,$white);
imagestring ($image,$font,0,0,$string,$black);
imagepng ($image);
imagedestroy($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.



Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie