使用php将图像保存到服务器

时间:2010-03-12 09:40:34

标签: php image upload

嘿,我有以下脚本,基本上一个flash文件发送一些数据并创建一个图像,然后为用户打开一个另存为对话框,以便他们可以将图像保存到系统中。这是问题所在,我如何将图像保存到我的服务器?

<?php

$to = $_POST['to'];
$from = $_POST['from'];
$fname = $_POST['fname'];
$send = $_POST['send'];

$data = explode(",", $_POST['img']);
$width = $_POST['width'];
$height = $_POST['height'];
$image=imagecreatetruecolor( $width ,$height );
$background = imagecolorallocate( $image ,0 , 0 , 0 );
//Copy pixels
$i = 0;
for($x=0; $x<=$width; $x++){
    for($y=0; $y<=$height; $y++){
        $int = hexdec($data[$i++]);
        $color = ImageColorAllocate ($image, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
        imagesetpixel ( $image , $x , $y , $color );
    }
}
//Output image and clean
#header("Content-Disposition: attachment; filename=test.jpg" );
header("Content-type: image/jpeg");

ImageJPEG( $image );
imagedestroy( $image ); 
?>

非常感谢帮助!

2 个答案:

答案 0 :(得分:4)

imagejpeg( $image, $filename );

会将图片保存到$filename。所以基本上可以做到

imagejpeg( $image, $filename );
imagedestroy( $image );
readfile( $filename );

而不只是调用

imagejpeg( $image );

答案 1 :(得分:-1)

稍微有点狡猾的方式,以节省重复的努力,就像是,

/* start output buffering to save output */
ob_start();
/* output image as JPEG */
imagejpeg( $image );
/* save output as file */
ob_flush();
file_put_contents( $filename, ob_get_contents() );