Creative Magic
Creative Magic

Reputation: 3151

Save BitmapData/ByteArray as a PNG file

I'm trying to save generated graphics as PNG files, but I'm stuck at actually saving the data as a file.

My steps are following:

here's my method in Haxe:

function saveImage():Void
{
    var ba:ByteArray = image.encode("png");

    var bi:haxe.io.BytesInput = new haxe.io.BytesInput(ba);

    var data = new format.png.Reader(bi).read();

    var out = sys.io.File.write("testRead.png",true);
    new format.png.Writer(out).write(data);

}

The image filed is a class variable type of BitmapData.

Please tell me what I'm doing wrong or how else to save BitmapData as a PNG image.

Upvotes: 3

Views: 2978

Answers (1)

Creative Magic
Creative Magic

Reputation: 3151

Thanks to the OpenFL community I found a way to save BitmapData as PNG images, here's the code:

// Creating a shape that we'll later save
var s:Sprite = new Sprite();
s.graphics.beginFill(0xFF0000, 1);
s.graphics.drawRect(0, 0, 110, 210);
s.graphics.endFill();

// Making a BitmapData from the Sprite
var image:BitmapData = new BitmapData( Std.int( s.width ), Std.int( s.height ), false, 0x00FF00);
image.draw(s);


// Saving the BitmapData
var b:ByteArray = image.encode("png", 1);
var fo:FileOutput = sys.io.File.write("test.png", true);
fo.writeString(b.toString());
fo.close();

The test.png file will appear in the package of the app, for example if you compile for mac: lime test mac you'll need to right click the .app you've created, select Show Package Contents, go to Contents>Resources and the test.png will be there.

Please remember that targeting Flash won't work because Flash Player has no access to the file system.

Upvotes: 4

Related Questions