Wednesday, March 3, 2010

Save image with flash and php


Here is the code to save the image through flash action script 2.0. Use the BitmapData class in action script 2.0 and get the data in string format that is basically value of each pixel and send the data 2 PHP file on the server. PHP file would prepare the header of the required image format and save the JPEG, PNG on the server as well and then at last when JPEG, PNG is saved than prompt user to download JPEG, PNG on their PC. :)
Action script 2.0
stop();
import flash.display.*;
 function sendImg () {
                var bmpData:BitmapData= new BitmapData(fighter_mc._width, fighter_mc._height);
                bmpData.draw(fighter_mc);
                var _pixels:Array = new Array();
                var _w:Number = bmpData.width;
                var _h:Number = bmpData.height;
                for (var i = 0; i<=_w; i++) {
                                for (var j = 0; j<=_h; j++) {
                                                var tmp = bmpData.getPixel(i,j ).toString(16);
                                                _pixels.push(tmp);
                                }
                }
                var lv:LoadVars = new LoadVars();
                lv.img = _pixels.toString();
                lv.height = _h;
                lv.width = _w;
                lv. sendAndLoad ("show.php", " lv ", "POST");
}
doneBtn.onPress = function() {
                sendImg();
};


PHP:
                $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-type: image/jpeg" );
                ImageJPEG( $image );
                imagedestroy( $image );              
?>

No comments:

Post a Comment