2010-11-16 67 views
2

我有以下GD库保存图像

$code = generateCode($characters); 
     /* font size will be 75% of the image height */ 
     $font_size = $height * 0.75; 
     $image = imagecreate($width, $height) or die('Cannot initialize new GD image stream'); 
     /* set the colours */ 
     $background_color = imagecolorallocate($image, 255, 255, 255); 
     $text_color = imagecolorallocate($image, 20, 40, 100); 
     $noise_color = imagecolorallocate($image, 100, 120, 180); 
     /* generate random dots in background */ 
     for($i=0; $i<($width*$height)/3; $i++) { 
     imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color); 
     } 
     /* generate random lines in background */ 
     for($i=0; $i<($width*$height)/150; $i++) { 
     imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color); 
     } 
     /* create textbox and add text */ 
     $textbox = imagettfbbox($font_size, 0, $font, $code) or die('Error in imagettfbbox function'); 
     $x = ($width - $textbox[4])/2; 
     $y = ($height - $textbox[5])/2; 
     imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code) or die('Error in imagettftext function'); 
     /* output captcha image to browser */ 
     header('Content-Type: image/jpeg'); 
     imagejpeg($image); 
     imagedestroy($image); 
     $_SESSION['security_code'] = $code; 

我挣扎保存图像的代码片段,但我能够渲染它,有没有办法救CAPCHA图像,而不是拒绝它?

+0

你没弄清楚你是否想将其保存到一个文件,数据库或一个变量。 – stillstanding 2010-11-16 13:05:07

+0

@stillstanding - 给文件 – Roland 2010-11-16 13:08:14

回答

3

使用输出缓冲:

ob_start(); 
imagepng(...); // or imagejpeg(...); 
$img=ob_end_clean(); 

,因为它是现在保存在一个变量,你可以将图像存储在数据库中(不保存到文件)或使其:

header('Content-type: image/png'); 
echo $img;