Turn Text into an Image using the PHP GD Library

Posted on May 25, 2009  |  Category: Tutorials

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.

<?php
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.


Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Short URL: http://bavotasan.com/?p=595

4 Responses to “Turn Text into an Image using the PHP GD Library”

  1. dreamer

    great! thank you. however; what about the utf 8? out of english characters?

    #3051
  2. I am having trouble creating the image for the advertisement at the top of the magazine basic. There is no browse and select jpg or anything. When I type text nothing shows up either. Do you just need to add the above text to a file and refer to it somehow. Please advise.

    Thanks

    #3339
    • Your comment is on the wrong page. To add an ad, you need to place an image link and a link. You need to upload your image either through FTP or the WordPress uploader.

      #3359
  3. Hi
    Is there some nifty way you can make this dynamically update based on a text string in e.g. a forum?
    I would like it to be used to include a text in an avatar I use on a forum, so it would be superb if it could pull the text from the forum where I have my public profile.

    #4651

Leave a Reply

To enter code in the comment box, please place it between <pre lang="php"> </pre> tags. You don't have to convert any characters to their hex/HTML code. Just add your code the way you would to any code editor.