PHP: Generate Dynamic Images from Text

Contributor Icon Contributed by William_Wilson Date Icon June 25, 2006  
Tag Icon Tagged: PHP programming

How to create images from text dynamically (quote generator)


Here is a piece of code i have used in the past. It uses a text file on the server, named quote.txt, but you could link it to any sort of inuput.

I have read many tutorials which claim to do the same, but most do not work, this WILL work, a test out link is provided, and this is the exact code used.


Header ("Content-type: image/gif");

$textfile = "quote.txt";
$quotes = array();
if(file_exists($textfile)){
$quotes = file($textfile);
srand ((float) microtime() * 10000000);
$string = '-'.$quotes[array_rand($quotes)];
$string = substr($string,0,strlen($string)-2);
}
else{
$string = "No 'Quote' available at this time.";
}
$font = 2;
$width = ImageFontWidth($font)* strlen($string);
$height = ImageFontHeight($font);
$im = ImageCreate($width,$height);

$x=imagesx($im)-$width ;
$y=imagesy($im)-$height;
$background_color = imagecolorallocate ($im, 242, 242, 242); //white background
$text_color = imagecolorallocate ($im, 0, 0,0);//black text
$trans_color = $background_color;//transparent colour
imagecolortransparent($im, $trans_color);
imagestring ($im, $font, $x, $y, $string, $text_color);

imagegif($im);
ImageDestroy($im);
?>

Try it out at: www.marvingohan.com

Questions/Comments: william_a_wilson@hotmail.com
-William. ยง (marvin_gohan)

Previous recipe | Next recipe |
 
blog comments powered by Disqus