PHP: Generate Dynamic Images from Text

Home -> Programming -> Web -> PHP

11363 views

From the computer of: William_Wilson (107 recipes)
Created: Jun 25, 2006


Add a comment

Add to:
Add to stumbleuponAdd to del.icio.usDigg itAdd to FURL

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.


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

Subscribe to the Tech-Recipes Newsletter

You can get tips like this delivered in your email every week!

Enter your Email

We will never, ever sell your email address or spam you.





Related recipes:

  PHP: Password Protect Your pages.
  PHP: determine the directory path of the server root
  PHP syntax: for loop basics
  PHP: Print the current year for copyright notices
  Make Wordpress Stop Replacing Double Dash with Em-dash
  PHP: Create a File on your Server
  Solve PHP error: Cannot modify header information - headers already sent
  PHP: Delete or expire a browser cookie
  PHP if statement syntax
  PHP: Upload Files to the server

 

Sponsored links

 

Login

Nickname

Password

Don't have an account yet? You can create one. As a registered user you have some advantages like theme manager, comments configuration and post comments with your name.