Haxe中保存位图为JPG格式

来源:互联网 发布:数据库基础是啥 编辑:程序博客网 时间:2024/04/29 23:13

Haxe NME支持载入jpg和png格式的图像文件,如果想要把内存中的位图即BitmapData保存成文件,则可以使用haxelib中的hxformat库,这里简单介绍下如何保存位图为jpg格式。

下面的代码可以把BitmapData编码成JPEG格式,并返回JPEG格式的字节数组。

    public function encodeJpeg(img: BitmapData) : Bytes {
        var bb = img.getPixels(new Rectangle(0, 0, img.width, img.height)); // 获取所有像素,像素数据以ARGB排列
        var output = new BytesOutput();
        var w = new format.jpg.Writer(output);
        w.write({ width: img.width, height: img.height, quality: 80, pixels: rox_toBytes(bb) });
        return output.getBytes();
    }

 

    /** 把ByteArray转换成haxe.io.Bytes,因为Bytes类在不同平台实现的差异性,这里需要用条件编译 */
    public static inline function rox_toBytes(byteArray: ByteArray) : Bytes {
        return #if flash Bytes.ofData(byteArray) #else cast(byteArray) #end;
    }

 如果想要进一步把字节数组保存为本地文件,则可用以下代码:

sys.io.File.saveBytes(“mytestfolder/image.jpg", encodeJpeg(image));