问题
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;
}
}
Thanks for the help!
回答1:
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;
}
}
Then there is no need to convert a BitmapImage to a byte[], just a file to byte[]. Yea!!!!
来源:https://stackoverflow.com/questions/24633439/convert-a-bitmapimage-to-byte-array-for-storage-in-sqlite-database