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