将位图图像转换为byte []数组以存储在sqlite数据库中 [英] Convert a bitmapimage to byte[] array for storage in sqlite database
问题描述
我已经使用filepicker从本地文件夹中选择一张照片,并将该图像分配给xaml页面中的图像控件.现在图像已经存在,我想将其保存到我的sqlite数据库中的byte []字段中.我已经尝试了多种搜索互联网的方法,但是大多数方法都涉及Windows 8.1 Windows Store应用程序中不可用的命名空间(例如System.Drawing).你能建议一种方法吗?这是我用来将byte []数组转换为位图图像的方法.我只想要相反的意思:
I have used filepicker to choose a photo from a local folder and have assigned that image to an image control in xaml page. Now that the image is there, I want to save it to a byte[] field in my sqlite database. I have tried numerous approaches from searching the internet but most involve a namespace that is not available (like System.Drawing) in windows 8.1 windows store app. Can you suggest a method? Here is the method I use to convert from byte[] array to a bitmap image. I just want the reverse of this:
//this converts VehPhoto Byte[] array to BitMapImage file
private async Task LoadImageAsync()
{
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
// Writes the image byte array in an InMemoryRandomAccessStream
// that is needed to set the source of VehicleBitMap.
using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
{
writer.WriteBytes(vehphoto);
await writer.StoreAsync();
}
var image = new BitmapImage();
await image.SetSourceAsync(ms);
vehiclebitmap = image;
}
}
感谢您的帮助!
推荐答案
我终于迷失了自己的问题的答案.从我身上浮现出来的是,一旦我从文件中加载照片图像,就可以将其放入字节数组中.因此,在我使用文件选择器选择了一张照片之后,将其转换为可在图像控件中使用的BitMapImage之后,便使用此代码将其分配给我的数据库元素:
I finally stumbled on the answer to my own question. It dawned on me that I could put the photo image into a byte array as soon as I load it from a file. So, right after I select a photo using filepicker, after converting it to a BitMapImage for use in the image control, I use this code to assign it to my database element:
byte[] fileBytes = null;
using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (DataReader reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
Vehicle.VehPhoto = fileBytes;
}
}
然后,无需将BitmapImage转换为byte [],只需将文件转换为byte [].是的!!!
Then there is no need to convert a BitmapImage to a byte[], just a file to byte[]. Yea!!!!
这篇关于将位图图像转换为byte []数组以存储在sqlite数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!