André Gil's Blog

UX, Dev, Tech and so on…

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:

1
2
3
4
5
6
7
8
[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:

1
2
3
4
5
6
7
8
[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:

1
2
3
4
5
6
7
8
[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?

3 Responses to “How to get BitmapData and ByteArray from Embed in Flex?”

  1. Breizo says:

    Andre,
    Very nice post and right on what I was looking for.
    One caveat though, as I banged my head on the wall:
    It looks like the concept works in the script section of an MXML file, but NOT from a pure as3 file. The compiler complains about an invalid type cast.

    Great job, thanks again!

  2. André Gil says:

    Hey Breizo,

    It’s really weird, it should work, since MXML files are always converted as AS3 classes when you compile them.

    Can you post the type cast error message, so I can try to figure out the problem?

    Cheers,
    Gil

  3. Mukti Muttaqin says:

    thank you… nice post solve my problem get bitmap Data from embed asset

Leave a Reply