2010-11-16 3 views
2

У меня есть фрагмент кода следующегоGD Lib, чтобы сохранить изображение

$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; 

Я изо всех сил, чтобы сохранить изображение, но я в состоянии сделать его, есть способ, чтобы сохранить эту картинку вместо ее откладывать?

+0

Вы не уточнялось, хотите ли вы, чтобы сохранить его в файл, базу данных или переменной. – stillstanding

+0

@stillstanding - в файл – Roland

ответ

3

да Вы можете, tip: второй параметр, если не установлен или NULL, поток необработанного изображения будет выводиться напрямую.

надеюсь, что это поможет.

http://php.net/manual/en/function.imagepng.php

3

Используйте буферизацию вывода:

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

Поскольку теперь сохраняется в переменной, вы можете сохранить изображение в базе данных (без сохранения в файл) или сделать его:

header('Content-type: image/png'); 
echo $img; 
Смежные вопросы