38

I have an image that was originally a PNG that I have converted to a byte[] and saved in a database. Originally, I simply read the PNG into a memory stream and converted the stream into a byte[]. Now I want to read the byte[] back and convert it to a BitmapImage, so that I can bind a WPF Image control to it.

I am seeing a lot of contradictory and confusing code online to accomplish the task of converting a byte[] to a BitmapImage. I am not sure whether I need to add any code due to the fact that the image was originally a PNG.

How does one convert a stream to a BitmapImage?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
David Veeneman
  • 18,912
  • 32
  • 122
  • 187
  • From another SO question: http://stackoverflow.com/questions/4444421/convert-a-byte-array-to-image-in-c-after-modifying-the-array/4444517#4444517 Does that work? – Metro Smurf Mar 18 '11 at 00:09
  • possible duplicate of [Creating WPF BitmapImage from MemoryStream png, gif](http://stackoverflow.com/questions/2097152/creating-wpf-bitmapimage-from-memorystream-png-gif) – Drew Noakes Apr 14 '15 at 09:46

2 Answers2

99

This should do it:

using (var stream = new MemoryStream(data))
{
    var bitmap = new BitmapImage();
    bitmap.BeginInit();
    bitmap.StreamSource = stream;
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.EndInit();
    bitmap.Freeze();
}

The BitmapCacheOption.OnLoad is important in this case because otherwise the BitmapImage might try to access the stream when loading on demand and the stream might already be closed.

Freezing the bitmap is optional but if you do freeze it you can share the bitmap across threads which is otherwise impossible.

You don't have to do anything special regarding the image format - the BitmapImage will deal with it.

Patrick Klug
  • 14,056
  • 13
  • 71
  • 118
5
 using (var stream = new MemoryStream(data))
        {
          var bi = BitmapFrame.Create(stream , BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
        }
Andreas
  • 3,843
  • 3
  • 40
  • 53
  • 2
    It would be helpful if you included an explanation as to why this code is helpful in answering the user's question. – Josh Burgess Nov 19 '14 at 15:02
  • To expand on this answer: BitmapFrame inherits from BitmapSource AND it has a factory method that accepts a stream as a source (as shown above). – Jon Bangsberg Jul 09 '21 at 22:31