views:

365

answers:

3

Hi, I'm using this script to simply create an image from text. What I would like to know is how to save the image instead of printing straight to browser;

// an email address in a string
     $string = $post[$key];

     // some variables to set
     $font  = 4;
     $width  = ImageFontWidth($font) * strlen($string);
     $height = ImageFontHeight($font);

     // lets begin by creating an image
     $im = @imagecreatetruecolor ($width,$height);

     //white background
     $background_color = imagecolorallocate ($im, 255, 255, 255);

     //black text
     $text_color = imagecolorallocate ($im, 0, 0, 0);

     // put it all together
     $image = imagestring ($im, $font, 0, 0,  $string, $text_color);

I know its probably just one line of code at the end but im not sure which GD function to use.

Any help would be much appreciated, Regards, Phil.

EDIT:

I have tried the following but just get a balnk black box;

 // an email address in a string
     $string = $post[$key];

     // some variables to set
     $font  = 4;
     $width  = ImageFontWidth($font) * strlen($string);
     $height = ImageFontHeight($font);

     // lets begin by creating an image
     $im = @imagecreatetruecolor ($width,$height);

     //white background
     $background_color = imagecolorallocate ($im, 255, 255, 255);

     //black text
     $text_color = imagecolorallocate ($im, 0, 0, 0);

     // put it all together
     imagestring ($im, $font, 0, 0,  $string, $text_color);

     imagepng($im, 'somefile.png');

       imagedestroy($im);
A: 

take a look at imagepng (or imagegif, imagejpeg...) - if you add a filename as second parameter, the image is saved as file.

oezi
+1  A: 

Pass a filename to the appropriate image-generating image*() function:

imagepng($image, 'somefile.png');
Ignacio Vazquez-Abrams
I have tried this but I just get a blank black box.
Phil Jackson
You get a blank black box because you're printing black text on a black background. Your `$background_color = imagecolorallocate($im, 255, 255, 255);` is just setting a variable called background_color to a value that represents white. imagecolorallocate only sets the background colour when used on palette-based images, not true-colour images.Try using imagecreate instead of imagecreatetruecolor, or if you need a true-colour image, use something like imagefilledrectangle to fill in your background before drawing the text.
Matt Gibson
A: 

Look at here http://www.php.net/manual/en/function.imagepng.php

Caspar