views:

396

answers:

1

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!

A: 

Hey Donny

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:

  • Loading in an image as a binary stream
  • Base64 encoding the bytes
  • Displaying it on the screen

Cheers

Danny Kopping
By the way, i'm using JP Auclair's Base64 class:http://jpauclair.net/2010/01/09/base64-optimized-as3-lib/
Danny Kopping