Confessions of a .NET Developer!

How to convert bytes to BitmapImage WPF

In this short post I will explain how convert array of bytes to BitmapImage in WPF ofcourse. I happened to use it when I needed to display Images in a DataGrid. And that Image is stored in a column named LargePhoto of data type VARBINARY(MAX) in AdventureWorksDW2008 Database. The VARBINARY(MAX) actually gets transformed into byte[] after mapping the Database to Entity Framework(ya of type EDMX). So I created a Converter to convert the bytes to BitmapImage.

There is one link I found which works in case of Silverlight, haven’t tried in WPF: Byte to BitmapImage in Silverlight

This one by Jobi Joy at StackOverflow also works: Byte to BitmapImage in WPF
But the problem is that stream is left open after conversion, which seems to me is not correct.
In the above case, the stream can be closed using this:

image.StreamSource.Dispose();

Okay so below is the code which will return a BitmapImage when a byte[] is given.

private BitmapImage GetBitmapImageFromBytes(byte[] bytes)
{   
   BitmapImage btm;
   using (MemoryStream ms = new MemoryStream(bytes))
   {
      btm = new BitmapImage();
      btm.BeginInit();
      btm.StreamSource = ms;
      // Below code for caching is crucial.
      btm.CacheOption = BitmapCacheOption.OnLoad;
      btm.EndInit();
      btm.Freeze();
   }
   return btm;
}

This line:

btm.CacheOption = BitmapCacheOption.OnLoad;

is very important. It says that the Image will be loaded into memory, and each request for the Image will be fetched from that memory store. So after closing or disposing the memory stream, the Image will be available in the memory cache.

I also found this piece of code written by Kent Boogart in CodePlex done in a different and in a better way but serving the same purpose : Byte to BitmapImage in WPF (By Kent Boogart)

Hope this helps! Thanks for reading! 🙂

December 25, 2011 Posted by | C Sharp, WPF | 1 Comment