将BitmapData/ByteArray保存为PNG文件

3

我正在尝试将生成的图形保存为PNG文件,但是我卡在了将数据实际保存为文件这一步。

我的步骤如下:

  • 创建一个图形对象
  • 通过draw()方法将图形转换为BitmapData对象
  • 使用encode方法对BitmapData对象进行编码以获取ByteArray对象。
  • 使用Format库(hxformat)保存文件

以下是我在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);

}
image 字段是 BitmapData 类型的类变量。
请告诉我我做错了什么或者如何将 BitmapData 保存为 PNG 图像。
1个回答

4

感谢OpenFL社区,我找到了一种将BitmapData保存为PNG图像的方法,以下是代码:

// 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();

test.png文件将出现在应用程序的包中,例如,如果您为Mac编译:lime test mac ,则需要右键单击创建的 .app 文件,选择“显示包内容”,进入“Contents> Resources”目录,然后就能找到test.png。

请记住,针对Flash的定位不起作用,因为Flash Player无法访问文件系统。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接