This was a big problem for me for a while. Because it’s a must to store a image in a database. But finally solved it. It’s worth writing a blog post because in Windows 10 some APIs has been changed. So let’s start.
We use a stream object to do this conversion.
To convert the bitmap image into a byte[] do the following ,(here I’m doing the conversion when the user selects a image using a file picker. Because in this method I need the storage file to open a stream).
- using System.IO;
-
- FileOpenPicker picker = newFileOpenPicker();
- picker.FileTypeFilter.Add(".bmp");
- picker.FileTypeFilter.Add(".png");
- picker.FileTypeFilter.Add(".jpg");
- StorageFile file = awaitpicker.PickSingleFileAsync();
- using(var inputStream = await file.OpenSequentialReadAsync())
- {
- var readStream = inputStream.AsStreamForRead();
- byte[] buffer = newbyte[readStream.Length];
- await readStream.ReadAsync(buffer, 0, buffer.Length);
- returnbuffer;
- }
To convert a byte[] into a bitmap image do the following,
-
- using(InMemoryRandomAccessStream stream = newInMemoryRandomAccessStream())
- {
- using(DataWriter writer = newDataWriter(stream.GetOutputStreamAt(0)))
- {
- writer.WriteBytes(array);
- awaitwriter.StoreAsync();
- }
- BitmapImage image = newBitmapImage();
- awaitimage.SetSourceAsync(stream);
- return image;
- }
Here’s a screenshot of a simple app I created using these methods.