BitmapData to PNG


how to convert a openfl.display.BitmapData to PNG in HTML5 ?


Using bitmapData.encode :slight_smile:

1 Like

I need a base64.encode() too ?

You won’t need to base64-encode if you are saving on the desktop, but if you are sending to a server you may need to base64-encode, or convert to an ArrayBuffer for filesaver.js on HTML5:

I try to convert this Flex as3 class with as32hx but it doesn’t work correctly

No need to convert. Haxe already has this.

Very good job, thanks.

I have a problem with bitmapDada.encode()

var ba:ByteArray = bitmapData.encode(bitmapData.rect, new PNGEncoderOptions());
trace(BitmapData.fromBytes( ba ).rect);
Main.hx:1: {
	x : 0, 
	y : 0, 
	width : 100, 
	height : 100

Main.hx:3: {
	x : 0, 
	y : 0, 
	width : 0, 
	height : 0

BitmapData.fromBytes works immediately on native platforms, but requires a little time for HTML5 before the pixels (and dimensions) are accessible.

BitmapData.loadFromBytes should work on all platforms, though

In as3

var png : ByteArray = new ByteArray();

var myBase64Encoder:Base64Encoder = new Base64Encoder();
myBase64Encoder.encodeBytes( png );
trace( myBase64Encoder.toString() );

the result is


but in haxe

var png : ByteArray = new ByteArray();

trace( Base64.encode(png) );

the result is


You’re right, PNGEncoder work now, and use filesaver.js.

In order to better support interaction with other software on the same system (and for improved performance), OpenFL (since version 6, I believe) uses the system default endianness rather than Endian.BIG_ENDIAN as the default for ByteArray. This could cause the difference you are seeing with your ActionScript 3 code. Either you could add png.endian = BIG_ENDIAN; or perhaps the Base64Encoder could be improved to support both kinds of endianness

You’re right, PNGEncoder work and I use filesaver.js