Add to Favorites

PHP putting text into an image

There are times when you will want to put text into an image and display that image. Perhaps you want to protect some text from bots, perhaps you want to use a custom font, or perhaps you are building a CAPTCHA implementation. Regardless of your motive, putting text into an image using the GD extension of php is simple. For this example, you must have TTF support in GD.

// font must be relative path or a full path, gd requires it
$font = './afont.ttf';
$width = 146;
$height = 46;
$font_size = 18;
$text = 'some text';

$img = imagecreate($width, $height);

// resource, x, y, color
imagefill($img,0,0,imagecolorallocate($img,255,255,255));

// resource, font size, angle, x, y, color, font file path, text
imagettftext($img, $font_size, 0, 1, 28,
	imagecolorallocate($img, 0,0,0), $font, $text);

// so the browser will display the image
header("Content-Type: image/JPEG");

// resource, filename, quality
imagejpeg($img,null,100);

// free the resource, this is a good habit so your
//script will release some memory
imagedestroy($img);

A couple things to note, the font path has to be a relative or full path so GD can load it; if you have errors then remove the header() call to see what the actual errors are.

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up