问题描述
我需要将图像转换为字节数组以将其存储在数据库中.而且我还需要将该数组转换回图像.我做了Google研究,但找不到解决方案,因为在 UWP
平台中某些api不可用.
I need to convert an image into a byte array to store it in a database. and also I need to convert that array back to the image. I did google research but I couldn't find a solution because in UWP
platform some api doesn't available.
推荐答案
我从这些文章中找到了解决方案,它们是 theoutlander 说.
I found the solution from these articles as theoutlander says.
要将图像转换为字节[],我将使用存储文件的'OpenSequentialReadAsyn()'方法.
To convert a image into a byte[] i'm going to use the 'OpenSequentialReadAsyn()' method of a storage file.
让我们假设我们的形象是文件".将其转换为字节数组,请执行以下操作
lets assume that our image is 'file'. to convert it into a byte array do the below
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 []转换回图像,请执行以下操作,
To convert the byte[] back into a image do the following,
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;
}
您可以在此文章.
这篇关于如何在uwp平台中将图像转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!