Working and creating images in Flex could not be as easy as it looks. When you load an image loaded from the remote server you will tipicaly receive a ByteArray data. The ByteArray image doesn't contain any information such as the width and height of that data. Moreover you must know when the entire bytearray it's been fully loaded on the client.
To do this we need to load the bytearray with the Loader Class.
So we need to extend an mx.control.Image Class and add the loader information:
private var _loader:Loader = new Loader();
Now wee need to implement a method to load the bytes:
public function loadBytes(bytes:ByteArray, context:LoaderContext = null):void
{
_loader.loadBytes(bytes, context);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onBytesLoaded);
}
This method will load the byte array image and add the listener to know when is ready.
After the event.complete handler will bring up with the loader information:
private function onBytesLoaded( e:Event ):void
{
source = _loader.content;
width = _loader.contentLoaderInfo.width;
height = _loader.contentLoaderInfo.height;
removeChild(_loader);
}
You can see that now we can set the source for the image and than set the correct width and height getting the information from the _loader.contentLoaderInfo.
Finally we remove the loader.
Here you can find the complete source for the ByteArrayImage Class:
The Class
package
{
import flash.display.Loader;
import flash.events.Event;
import flash.system.LoaderContext;
import flash.utils.ByteArray;
import mx.controls.Image;
public class ByteArrayImage extends mx.controls.Image
{
private var _loader:Loader = new Loader();
public function ByteArrayImage()
{
}
override protected function createChildren():void
{
_loader.visible = false;
addChild(_loader);
}
public function loadBytes(bytes:ByteArray, context:LoaderContext = null):void
{
_loader.loadBytes(bytes, context);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onBytesLoaded);
}
private function onBytesLoaded( e:Event ):void
{
source = _loader.content;
width = _loader.contentLoaderInfo.width;
height = _loader.contentLoaderInfo.height;
removeChild(_loader);
}
}
}
A simple implementation:
import flash.image.JPEG;
import flash.image.PNG32;
myJPG:ByteArray = new JPEG( bitmapData , 300, 300, 80 );
myPNG:ByteArray = new PNG32( bitmapData , 1500, 1260 );
myByteImage:ByteArrayImage = new ByteArrayImage();
myByteImage.loadBytes( myJPG or myPNG );
Reference:
ByteArray LiveDocs
Loader LiveDocs