Convert memory stream to BitmapImage?

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.

Leave a Comment