将bitmapimage转换为byte[]数组以存储在sqlite数据库中



我使用filepicker从本地文件夹中选择一张照片,并将该图像分配给xaml页面中的图像控件。现在图像已经在那里了,我想把它保存到我的sqlite数据库中的byte[]字段中。我已经尝试了无数的方法从搜索互联网,但大多数涉及一个不可用的命名空间(如System.Drawing)在windows 8.1 windows商店应用程序。你能建议一个方法吗?下面是我用来将byte[]数组转换为位图图像的方法。我只是想把这个反过来:

   //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;
        }
    }

谢谢你的帮助!

我终于找到了自己问题的答案。我突然意识到,只要从文件中加载照片图像,我就可以将其放入字节数组中。因此,在我使用filepicker选择照片之后,在将其转换为BitMapImage用于图像控件之后,我使用以下代码将其分配给我的数据库元素:

            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[]。是的! !

最新更新