window.readPixels coming up blank

Hi all,
I am attempting to capture a screen shot and save it for later use. Right now I am getting data but when I restore it back to an image, it appears as a black square. If I use an online Base64 encoder instead with a different image and replace that data, it restores as expected within OpenFL. Here’s the capture code:

var c = getViewComponent();
var w:HTML5Window = cast( Lib.current.stage.window);
var image = w.readPixels(new Rectangle(c.x,c.y,c.width,c.height));
var imageData = image.encode(ImageFileFormat.JPEG,60); 
var b64 = Base64.encode(imageData);
lsp.savePlanImageRender(b64);  //saves to Local Storage in HTML5 browser

I believe it is likely relevant that I have not enabled “openfl-share-context” in the project.xml. This was causing many other problems for me. The view component I am capturing is very likely in its own context. Does anyone have a suggestion as to what I need to tweak in order for the image data to capture properly? Thanks in advance.

Update:

  • I tried capturing the image with context sharing enabled. It did not help.
  • I tried encoding the image as PNG instead of JPG. It came out all white instead of all black.
1 Like

I think that window.readPixels must be called just before swapping buffers or it will read pixels from the front buffer (which may already be clear) rather than a buffer that’s full of visual content.

Can you use bitmapData.draw instead?

2 Likes

Hey @singmajesty thanks for this. Since I really wanted an image from Away3D I figured out how to get it using:

imageDump = new BitmapData(Math.floor(this.width),Math.floor(this.height),false);
_view.renderer.queueSnapshot(imageDump);
_view.render();

…later encoding it using:

var imageData = imageDump.image.encode(ImageFileFormat.JPEG,50);
var b64 = Base64.encode(imageData); //to save as String

I may try your solution in the future!

3 Likes