Convert a bitmapimage to byte[] array for storage in sqlite database

百般思念 提交于 2019-12-12 02:15:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!