问题
I'm trying to load an image file that's right next to the .SWF file. Something like this:
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, function(e:Event):void {
trace(typeof(loader.data));
graphic = spritemap = new Spritemap(loader.data, 32, 32);
...
}
But this is the output I get:
object
[Fault] exception, information=Error: Invalid source image.
The thing is loader.data has the image's bytes but is not a BitmapData instance and that's what Spritemap is expecting.
How to convert to BitmapData?
Thanks
回答1:
// define image url
var url:URLRequest = new URLRequest("http://sstatic.net/ads/img/careers2-ad-header-so.png");
// create Loader and load url
var img:Loader = new Loader();
img.load(url);
// listener for image load complete
img.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
// attaches the image when load is complete
function loaded(e:Event):void
{
var bitmap:Bitmap = e.target.content;
doStuffWithBitmapData(bitmap.bitmapData);
addChild(bitmap);
// remove listener
e.target.removeEventListener(Event.COMPLETE, loaded);
}
/**
* Handle loaded BitmapData
* @param bmd The loaded BitmapData
*/
function doStuffWithBitmapData(bmd:BitmapData):void
{
trace(bmd);
// your code
}
Basically;
You should be using Loader
, not URLLoader
. You can access the BitmapData
of the loaded Bitmap
with bitmap.bitmapData
.
来源:https://stackoverflow.com/questions/6091678/urlloader-data-to-bitmapdata