Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URLLoader data to BitmapData

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

like image 921
John Crichton Avatar asked May 23 '11 00:05

John Crichton


1 Answers

// 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.

like image 180
Marty Avatar answered Sep 28 '22 15:09

Marty