9

How to send a jpg image as ByteArray from as3 to javascript? And how to convert ByteArray to image in javascript?

3 Answers 3

4

Take your DisplayObject (Sprite/MovieClip/whatever) and convert it to a BitmapData:

myBitmapData.draw(mySprite);

Convert that to a PNG using adobe's AS3CoreLib

myByteArray = PNGEncoder.encode(myBitmapData);

Convert that to Base64 using Flex's Base64Encoder:

myBase64Encoder.encodeBytes(myByteArray);

Then export actionscript variables to Javascript using ExternalInterface.

Sign up to request clarification or add additional context in comments.

1 Comment

after more than 3 years... and someone else found this post very useful !! thank you so much !!
2

The JavaScript and DOM implementations of current web browsers don't really have good mechanisms for doing this sort of thing.

Your best bet is to have your AS3 return a DATA protocol URI with a base64-encoded version of the image. Modern browsers (IE8+, FF2+, etc) will accept a DATA URI as the SRC of an IMG tag and will render the image contained therein.

http://en.wikipedia.org/wiki/Data_URI_scheme

You'll have to have a AS3 expert explain how to turn an byte-array into a base64-encoded string, but it cannot be that hard.

2 Comments

Indeed, that won't work in older browser versions. Without using a DATA URI, there's no other way to do this with the DOM itself.
For the record, the way to do the conversion is: Take your DisplayObject (Sprite/MovieClip/whatever), convert it to BitmapData (myBitmapData.draw(mySprite);), convert that to a PNG using adobe's AS3CoreLib (myByteArray = PNGEncoder.encode(myBitmapData);), convert that to Base64 using Flex's Base64Encoder (myBase64Encoder.encodeBytes(myByteArray);), then export that to some Javascript function using ExternalInterface.
0

There is a method in this class that does that:

https://github.com/monkeypunch3/flexcapacitor/blob/master/MainLibrary/src/com/flexcapacitor/utils/DisplayObjectUtils.as

calling

var data:String = DisplayObjectUtils.getBase64ImageDataString(); 

will return this string:

data:image/png;base64,...

You then set the src of an img in html to that value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.