Reputation: 89
I would like to be able to move images into and out of Flex by converting back and forth between ByteArrays. I've been having some trouble with this, so I designed a simple test program, and even that I can't get to work. Here's the code I'm trying right now:
protected function button3_clickHandler(event:MouseEvent):void
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler2);
loader.load(new URLRequest("file:///c:/win.jpg"));
}
private function loaderCompleteHandler2(event:Event):void
{
var loader:Loader = (event.target as LoaderInfo).loader;
var bmp:Bitmap = Bitmap(loader.content);
image1.source = bmp;
myBmpData = bmp.bitmapData;
myByteArray = bmp.bitmapData.getPixels(myBmpData.rect);
}
protected function button4_clickHandler(event:MouseEvent):void
{
var loader:Loader = new Loader();
loader.loadBytes(myByteArray);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loaderCompleteHandler);
}
private function loaderCompleteHandler(event:Event):void
{
var loader:Loader = (event.target as LoaderInfo).loader;
var bmp:Bitmap = Bitmap(loader.content);
image1.source = bmp;
}
So far the process follows top to bottom: Click button 3, image displays, everything is going well. Click button 4, and I get "Error #2044: Unhandled IOErrorEvent:. text=Error #2124: Loaded file is an unknown type." after the line "loader.loadBytes(myByeArray);" in the function button4_clickHandler. As far as I can tell I'm using everything as intended. I would really appreciate any suggestions to get me moving in the right direction. Thanks!
Upvotes: 2
Views: 11055
Reputation: 1226
Danny Kopping's solution above should work, and URLLoader should perform better than Loader.load().
But then, the use of Base64Image is IMHO not optimal. Internally, Base64Image uses Loader.loadBytes & decodes the Base64 beforehand - so effectively, there is an encode to Base64 followed by a decode.
I suggest simply using the loadBytes method of Loader like this:
private function loaded(event:Event):void
{
var loader:Loader = new Loader();
loader.loadBytes(event.currentTarget.data as ByteArray);
}
I don't know of a way that would avoid using Loader altogether.
Upvotes: 0
Reputation: 5190
Check out the following code:
var l:URLLoader = new URLLoader(new URLRequest("/path/to/image"));
l.dataFormat = URLLoaderDataFormat.BINARY;
l.addEventListener(Event.COMPLETE, loaded);
private function loaded(event:Event):void
{
var ba:ByteArray = event.currentTarget.data as ByteArray;
b64Img.source = Base64.encode(ba);
}
The b64Img object that i set the source property on is a Base64Image which is a part of the great FlexLib project. So, in effect, what you are doing is the following:
Cheers
Upvotes: 1