本文主要是介绍Haxe中保存位图为JPG格式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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));
这篇关于Haxe中保存位图为JPG格式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!