Some Pixels en / pt

How to get BitmapData and ByteArray from Embed in Flex?

When you want to manipulate images and other file types in Flex, most of the time you need the BitmapData or the ByteArray from that file. Most people know how to get it when they are using the Loader, but it's harder to find information about how to get it using Embedded files. It's really easy to do that, let me show you how!

If you want to Embed some image (JPEG, GIF or PNG) in Flex, you have to Embed it into a Class. What most people doesn't know is that the type of this Class will by the BitmapAsset and that BitmapAsset is a subclass of the Bitmap class. So you can do this:

[Embed(source="image.png")]
public var MyEmbed:Class;

private function getBitmapData():BitmapData
{
    var bitmapAsset:BitmapAsset = new MyEmbed();
    return bitmapAsset.bitmapData;
}

Now, to get the ByteArray, you need a little trick! You have to add the parameter mimeType="application/octet-stream" to the Embed metadata. With this parameter, the Class type will be ByteArrayAsset and that's a subclass of ByteArray. So you can do this:

[Embed(source="image.png",mimeType="application/octet-stream")]
public var MyEmbed:Class;

private function getByteArray():ByteArrayAsset
{
    var byteArrayAsset:ByteArrayAsset = new MyEmbed();
    return byteArrayAsset;
}

This way, you can even Embed some TXT or XML file in your application and read it very easily! The ByteArray can be converted to a String:

[Embed(source="myTextFile.txt",mimeType="application/octet-stream")]
public var MyEmbed:Class;

private function readEmbeddedTxt():String
{
    var byteArrayAsset:ByteArrayAsset = new MyEmbed();
    return byteArrayAsset.toString();
}

Easy, huh?