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:

<?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); 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.

Copy from http://bavotasan.com/2009/turn-text-into-an-image-using-the-php-gd-library/

By dbglory Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s