pfunc
pfunc

Reputation: 1305

Converting a flex component w/images to bitmap

I am trying to take images I am placing in a flex canvas component to a bitmap. I was able to get to the point where I'm not getting an error but then no image shows up and the image I save out as a jpg is blank. I imagine I'm not setting the bitmap data correctly but can't figure out what I am doing wrong.

Here is the code where I am converting it to a bitmap:

var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(_renderPop);
   var imageByteArray:ByteArray = imageSnap.data as ByteArray;
   var bLoader:Loader = new Loader();
   bLoader.loadBytes(imageByteArray);

   var bmd:BitmapData = new BitmapData(500,500);
   bmd.draw(bLoader);

   var imgTest:Image = new Image();
   imgTest.source = bmd;
   _renderPop.renderCanvas.addChild(imgTest);



   var fileRef:FileReference = new FileReference();
   fileRef.save(bLoader, 'testImage.jpg');

_renderPop.renderCanvas is where I am placing the images. Anybody see anything wrong?

Upvotes: 0

Views: 1595

Answers (2)

Oleksandr Tsurika
Oleksandr Tsurika

Reputation: 980

Your "loader" code is wrong. Just after capturing image you may at once save data with FileReference:

var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(_renderPop);
var fileRef:FileReference = new FileReference();    
fileRef.save(imageSnap.data, 'testImage.png'); 

That imageSnap contains not BitmapData but png image bytes. In order to show image you need to capture BitmapData but not image and create Bitmap from bitmap data:

var bmd:BitmapData = ImageSnapshot.captureBitmapData(_renderPop);
var imgTest:Image = new Image();
imgTest.source = new Bitmap(bmd);
_renderPop.renderCanvas.addChild(imgTest); 

In result locally testImage.png is created on file system and it is shown in canvas. If you need jpg you should specify:

var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(_renderPop, 0, new JPEGEncoder());

Upvotes: 1

Danny Kopping
Danny Kopping

Reputation: 5190

In your code:

var bLoader:Loader = new Loader();
bLoader.loadBytes(imageByteArray);

...you're assuming that the bytes are being loaded immediately; try putting an event listener on the loader as follows:

bLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);

private function completeHandler(event:Event):void
{
    // ... the rest of your code goes here
}

The loadBytes functions works like the load function in that they are both asynchronous processes so you'll need the event listener. It is a little counter-intuitive, and i've made the same mistake myself several times.

If that doesn't work, maybe leave out the contentLoaderInfo property, but the above should work...

Let me know if you come right :)

Upvotes: 0

Related Questions