Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert memory stream to BitmapImage?

Tags:

wpf

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?

like image 629
David Veeneman Avatar asked Mar 18 '11 00:03

David Veeneman


2 Answers

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.

like image 169
Patrick Klug Avatar answered Nov 07 '22 03:11

Patrick Klug


 using (var stream = new MemoryStream(data))
        {
          var bi = BitmapFrame.Create(stream , BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
        }
like image 5
Andreas Avatar answered Nov 07 '22 03:11

Andreas