开发者

Image as ByteArray in Flex

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 th开发者_StackOverflow中文版e 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!


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'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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜