user1587872
user1587872

Reputation: 365

Javascript + ActionScript: How to convert bytearray returned from Actionscript to image in Javascript

I have bytearray returned from ActionScript to Javascript through ExternalInterface call. Now, i have to convert this byteaarray to image in Javascript code. pls help...with any sample code...

Thanks in advance...

Upvotes: 3

Views: 1097

Answers (2)

Dreen
Dreen

Reputation: 7226

I see two possible solutions to this problem, neither of which I have tested so try them out:

HTML5 Canvas

First, using ActionScript convert your byte array to integer array. You will need four values for:

  • Red
  • Green
  • Blue
  • Alpha

Transfer this to Javascript, either using string representation or plain numbers and then load these numbers into the canvas:

var canvasData = ; // data from actionscript
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var imgData=ctx.createImageData(100,100);
for (var i=0;i<imgData.width*imgData.height*4;i+=4)
{
  imgData.data[i+0]=canvasData[i][0]; // red
  imgData.data[i+1]=canvasData[i][1]; // green
  imgData.data[i+2]=canvasData[i][2]; // blue
  imgData.data[i+3]=canvasData[i][3]; // alpha
}
ctx.putImageData(imgData,10,10);

Base64-encoded through CSS

If you don't want to rely on HTML5, use ActionScript to convert the byte array to a base64 string and then insert the image using the following css rule:

background-image: url(data:image/png;base64,__base64_data__);

and replace __base64_data__ with the generated string. This could be done dynamically using JQuery:

$('#img').css("background-image", "url(data:image/png;base64,__base64_data__)"); 

This also seems to be a much more efficient method than HTML5 Canvas, although actual performance will depend on the image size.

Upvotes: 4

Delapouite
Delapouite

Reputation: 10157

You can store your data in an ArrayBuffer and inject this into a canvas to display as explained here : https://hacks.mozilla.org/2011/12/faster-canvas-pixel-manipulation-with-typed-arrays/

Upvotes: 0

Related Questions