Creating image from text in PHP

Downloads:1530 Bookmark this code Bookmark and Share
Rank : 4/5
Rated by : 2 user(s)
Developer:Andrew R  |   13 submission(s)
Date Uploaded:November 01,2009
Level:Intermediate
Size: 0 Bytes
Category:PHP -> Images/Graphics
Developer Says:

Sometimes it is required to display email addresses as images to safegaurd against spammers and to protect emails being captured by screen scraping. So the code below is a function that receives text to be displayed on the image. The size of image, fonts and colors can be customized. The text is centered horizontally and vertically in the image. A font file should be placed in the path specified in the code below

<?
	/*
	*	Sometimes it is required to display email addresses as images to safegaurd against spammers and to protect emails being captured by screen scraping. So the code below is a function that receives text to be displayed on the image. The size of image, fonts and colors can be customized. The text is centered horizontally and vertically in the image. A font file should be placed in the path specified in the code below
	*/
	function createSourceImage($text){
		if(trim($text)!=''){
			$width=420;
			$height=100;
			$img=imagecreatetruecolor($width,$height);
			$fill_color=imagecolorallocate($img,220,230,235);
			$text_color=imagecolorallocate($img,30,64,90);
			$font='arial.ttf';
			imagefilledrectangle($img,0,0,$width,$height,$fill_color);
			imagerectangle($img,1,1,$width-2,$height-2,$text_color);
			$bbox=imagettfbbox(34,0,$font,$text);
 
			$x = $bbox[0] + (imagesx($img) / 2) - ($bbox[4] / 2);
			$y = $bbox[1] + (imagesy($img) / 2) - ($bbox[5] / 2);
 
			imagettftext($img,34,0,$x,$y,$text_color,$font,$text);
			return $img;
		}
	}
	header("Content-type:image/jpeg");
	$img=createSourceImage("Yahoo News");
	imagejpeg($img,'',80);
 ?>

The above code was highlighted with Neat Highlighter


User Reviews
Joe
[05-Mar-2010]
#1

There is something I'm uncertain about - where is the font file "arial.ttf" (somewhere on the server, or somewhere on a users client machine)?

 

Andrew
[05-Mar-2010]
#2

The font file should be in the same directory where your php file is (In the above code). You can copy arial.ttf from the fonts directory and place it where it is accessible by your php script.

Leave a Comment
Age (Required, will not be shown)
Name
Email (Required, will not be shown)
Website (Optional, starting with http://)
 
Rate this code
Poor   1 2 3 4 5   Outstanding
Are you human ?

Enter the code shown above