[as3]
import flash.display.Bitmap;
import flash.display.Loader;
import fl.controls.Button;
import flash.net.FileReference;
import flash.net.FileFilter;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.events.MouseEvent;
import flash.utils.ByteArray;

// initializing FileReference
var imageFilter=new FileFilter("Images", "*.jpg;*.jpeg;*.gif;*.png");
var fileR:FileReference=new FileReference();
fileR.addEventListener(Event.CANCEL, cancelHandler);
fileR.addEventListener(Event.SELECT, selectHandler);
fileR.addEventListener(ProgressEvent.PROGRESS, progressHandler);
fileR.addEventListener(Event.COMPLETE, completeHandler);

// creating button using Flash component
var pickbutton:Button=new Button();
pickbutton.x=pickbutton.y=10;
pickbutton.label="Select Image";
pickbutton.addEventListener(MouseEvent.CLICK,selectImage);
addChild(pickbutton);

function selectImage(e:MouseEvent):void{ // click button
fileR.browse([imageFilter]); // browse files
}
function selectHandler(e:Event):void{ // file selected
trace("selectHandler: "+fileR.name);
fileR.load(); // load file
}
function cancelHandler(e:Event):void { // cancel select
trace("cancelHandler");
}
function progressHandler(e:ProgressEvent):void { // progress event
trace("progressHandler: loaded="+e.bytesLoaded+" total="+e.bytesTotal);
}
function completeHandler(e:Event):void { // file loaded
trace("completeHandler: " + fileR.name);
var ba:ByteArray=fileR.data; // get data
var loader:Loader=new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loaded);
loader.loadBytes(ba); // load with Loader
}
function loaded(e:Event):void{ // bitmap loaded
while(numChildren>1){ // remove any previous bitmaps on stage
removeChildAt(0);
}
var bm:Bitmap = e.currentTarget.loader.content as Bitmap;

// resize bitmap if larger than stage
if(bm.width>stage.stageWidth||bm.height>stage.stageHeight){
var xscale:Number=stage.stageWidth/bm.width;
var yscale:Number=stage.stageHeight/bm.height;
if(xscale<yscale){
bm.scaleX=bm.scaleY=xscale;
}else{
bm.scaleX=bm.scaleY=yscale;
}
}

// center bitmap
bm.x=Math.abs(bm.width-stage.stageWidth)/2;
bm.y=Math.abs(bm.height-stage.stageHeight)/2;

// add to bottom
addChildAt(bm,0);
}
[/as3]

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation