Convert a Bitmapimage into a Byte Array and Vice Versa in UWP Platform

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.

Stream

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).

  1. using System.IO;  
  2. //call this when selecting an image from the picker  
  3. FileOpenPicker picker = newFileOpenPicker();  
  4. picker.FileTypeFilter.Add(".bmp");  
  5. picker.FileTypeFilter.Add(".png");  
  6. picker.FileTypeFilter.Add(".jpg");  
  7. StorageFile file = awaitpicker.PickSingleFileAsync();  
  8. using(var inputStream = await file.OpenSequentialReadAsync())  
  9. {  
  10.     var readStream = inputStream.AsStreamForRead();  
  11.     byte[] buffer = newbyte[readStream.Length];  
  12.     await readStream.ReadAsync(buffer, 0, buffer.Length);  
  13.     returnbuffer;  
  14. }  
To convert a byte[] into a bitmap image do the following,
  1. //This task will return aimage from provided the byte[].  
  2. using(InMemoryRandomAccessStream stream = newInMemoryRandomAccessStream())  
  3. {  
  4.     using(DataWriter writer = newDataWriter(stream.GetOutputStreamAt(0)))  
  5.     {  
  6.         writer.WriteBytes(array);  
  7.         awaitwriter.StoreAsync();  
  8.     }  
  9.     BitmapImage image = newBitmapImage();  
  10.     awaitimage.SetSourceAsync(stream);  
  11.     return image;  
  12. }  
Here’s a screenshot of a simple app I created using these methods.

run

Ebook Download
View all
Learn
View all