gpt4 book ai didi

c# - 如何在 uwp 平台中将图像转换为字节数组

转载 作者:太空狗 更新时间:2023-10-30 00:30:33 26 4
gpt4 key购买 nike

我需要将图像转换为字节数组以将其存储在数据库中。而且我还需要将该数组转换回图像。我进行了谷歌研究,但找不到解决方案,因为在 UWP 平台中,某些 API 不可用。

最佳答案

我从这些文章中找到了解决方案 theoutlander说。

要将图像转换为 byte[],我将使用存储文件的“OpenSequentialReadAsyn()”方法。

假设我们的图像是"file"。将其转换为字节数组执行以下操作

 using (var inputStream = await file.OpenSequentialReadAsync())
{
var readStream = inputStream.AsStreamForRead();

var byteArray = new byte[readStream.Length];
await readStream.ReadAsync(byteArray, 0, byteArray.Length);
return byteArray;
}

要将 byte[] 转换回图像,请执行以下操作,

 using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
{
writer.WriteBytes(this.byteArray);
await writer.StoreAsync();
}
var image = new BitmapImage();
await image.SetSourceAsync(stream);
return image;

}

您可以在此 article 中找到更多信息.

关于c# - 如何在 uwp 平台中将图像转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35111635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com