views:

36

answers:

2

Hey i have the following script, basicaly a flash file sends it some data and it creates a image and then opens a save as dialog box for the user so that they can save the image to there system.Here the problem comes in, how would i go about also saving the image to my server?

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

Help would be greatly appreciated!

+1  A: 
imagejpeg( $image, $filename );

will save the image to $filename. So essentially could do

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

instead of just calling

imagejpeg( $image );
Stefan Gehrig
A: 

The slightly fancier way so save on duplicated effort would be something like,

/* 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() );
Steve-o
Be aware that'll you need approx. twice the memory using this approach as you'll have the image in memory twice.
Stefan Gehrig
You'll have uncompressed and compressed, considering uncompressed >> compressed it's not much of an issue. In IO restricted environments it would be better to output to the client before the disk.
Steve-o
Hey thanks for the help! How would i go about specifying the directory to which the file should be save?
salmon
$filename can be simply a filename, relative path or full path as per usual PHP rules. e.g. '/srv/cache/myphoto.jpeg'.
Steve-o