堆栈的小伙伴好奇他有一个数组,数组里面是 BGRA 的像素,他需要将这个数组转换为 PNG 文件 在 UWP 可以使用 BitmapEncoder 将像素数组加密为文件
在使用 BitmapEncoder 之前需要要求有像素数组,像素数组的规律有要求,按照 BGRA 按照顺序的数组,同时要求知道像素的原图的像素宽度。因为存放像素数组使用的是一维的数组,如果不知道图片宽度,那么就不知道这个图片的像素是对应数组哪个
通过下面方法可以转换像素数组到文件
private async Task ByteToPng(byte[] byteList, int width, int height, IRandomAccessStream file)
{
try
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, file);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint) width, (uint) height, 96,
96, byteList);
await encoder.FlushAsync();
}
catch (Exception e)
{
}
}
这里的 IRandomAccessStream 就是 StorageFile 打开文件
private async Task SaveToFileAsync(byte[] byteList, int width, int height, IStorageFile file)
{
using (var stream = (await file.OpenStreamForWriteAsync()).AsRandomAccessStream())
{
await ByteToPng(byteList, width, height, stream);
}
}
通过这个方法,可以传入数组和图片的宽度和高度,保存的文件,就可以将像素数组保存到 png 文件
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有