How to Convert byte array to BitmapImage


Recently, I came across a interesting question on how to convert from a byte array to BitmapImage. The typicall scenario is when given an image represented by BitmapImage object it should be stored in a database as byte[].

The code I’m going to show below has been extracted from Stackoverflow.com but I found it in several sites after googling, therefore I can’t point out the author.

The code is quite simple just use:

   1: public byte[] GetBytes(BitmapImage bi) 
   2: { 
   3:     WriteableBitmap wbm = new WriteableBitmap(bi); 
   4:     return wbm.ToByteArray(); 
   5: } 

 

Where ToByteArray method is:

   1: public static byte[] ToByteArray(this WriteableBitmap bmp) 
   2: { 
   3:     // Init buffer 
   4:     int w = bmp.PixelWidth; 
   5:     int h = bmp.PixelHeight; 
   6:     int[] p = bmp.Pixels; 
   7:     int len = p.Length; 
   8:     byte[] result = new byte[4 * w * h]; 
   9:  
  10:     // Copy pixels to buffer 
  11:     for (int i = 0, j = 0; i < len; i++, j += 4) 
  12:     { 
  13:         int color = p[i]; 
  14:         result[j + 0] = (byte)(color >> 24); // A 
  15:         result[j + 1] = (byte)(color >> 16); // R 
  16:         result[j + 2] = (byte)(color >> 8);  // G 
  17:         result[j + 3] = (byte)(color);       // B 
  18:     } 
  19:  
  20:     return result; 
  21: } 

Another way to achieve it is using ImageTools for Silverlight. I have used it in several Windows Phone projects, specially animating gif images, and it contains a method that could be used in order to convert BitmapImage from and to byte[] by just using a few lines of code:

   1: using (var writingStream = new MemoryStream()) 
   2:                         { 
   3:                             var encoder = new PngEncoder 
   4:                             { 
   5:                                 IsWritingUncompressed = false 
   6:                             }; 
   7:                             encoder.Encode(bitmapImageInstance, writingStream); 
   8:                             // ...
   9:                         } 

Both solutions works fine. The first one does not need any kind of library reference meanwhile the second one needs ImageTools library (that could be reached in Nuget).

, , ,

Comments are closed.