I’ve created an image saving class for one of my projects which uses a URLRequest and FileReference.save to get an image from my server and save it to the users harddrive. I’m using this instead of the more common php method because I’m not good at writing php and I don’t like the seemingly obligatory browser pop-up.
This code works, but it requires the user to click a button in the swf twice, once to load the image from the server to a BitmapData object, and then again to activate the FileReference.save method. Flash doesn’t allow automatic saving without direct user input.
What I would like to know is if there is a way to get all this functionality under just one button press?
This is the code I’m working with:
public function create():void
{
_infoTxt = new Bitmap(_btnArray[0]);//text = "save wallpaper"
_infoTxt.x = 0;
_infoTxt.y = 0;
addChild(_infoTxt);
//create 6 buttons for different wallpaper sizes
for (var i:int = 0; i < _resArray.length; i++)
{
var saveBmp:Bitmap = new Bitmap(_btnArray[i+5]);
var saveTxt:Sprite = new Sprite();
saveTxt.name = _resArray*;
saveTxt.addChild(saveBmp);
saveTxt.x = 0
saveTxt.y = (_infoTxt.height + saveTxt.height*(i));//_padding)*(i+1);
saveTxt.addEventListener(MouseEvent.CLICK, getImg, false, 0, true);
addChild(saveTxt);
}
}
//click button to load image data from external file
private function getImg(e:MouseEvent):void
{
_infoTxt = new Bitmap(_btnArray[1]);//text = "one moment please..."
addChild(_infoTxt);
_imgName = "ssM"+String(_lvl)+"_"+e.target.name+".jpg";
var imgRequest:URLRequest = new URLRequest("img/"+_imgName);
//var imgRequest:URLRequest = new URLRequest("http://www.sergiovanpul.com/SP2D/img/"+_imgName);
var loader:Loader = new Loader();
loader.load(imgRequest);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded);
}
//when the image has loaded you can get its BitmapData
private function imgLoaded(e:Event):void
{
_img = e.target.content.bitmapData;
_infoTxt = new Bitmap(_btnArray[2]);//text = "ready to save"
_infoTxt.y = -10;
_infoBtn.graphics.beginFill(0x000000, 0);
_infoBtn.graphics.drawRect(_infoTxt.x, _infoTxt.y-_infoTxt.height/3, _infoTxt.width, _infoTxt.height*1.5);
_infoBtn.graphics.endFill();
//another click is required to start the saveImg function, which is rather cumbersome
_infoBtn.addEventListener(MouseEvent.CLICK, saveImg, false, 0, true);
addChild(_infoTxt);
addChild(_infoBtn);
}
//finally the image is saved to harddrive
private function saveImg(e:MouseEvent):void
{
var imgEncoder:JPGEncoder = new JPGEncoder(100);
var byteArray:ByteArray = imgEncoder.encode(_img);
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(Event.SELECT, onSaveFileSelected, false, 0, true);
fileRef.save(byteArray, _imgName);
_infoBtn.removeEventListener(MouseEvent.CLICK, saveImg);
_infoTxt.y = 0;
removeChild(_infoTxt);
removeChild(_infoBtn);
}
And here is a working example in a game:
http://www.sergiovanpul.com/SP2D/sketchySlides.html