Convert memory stream to BitmapImage?

后端 未结 2 1011
渐次进展
渐次进展 2020-11-27 15:57

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

相关标签:
2条回答
  • 2020-11-27 16:43
     using (var stream = new MemoryStream(data))
            {
              var bi = BitmapFrame.Create(stream , BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
            }
    
    0 讨论(0)
  • 2020-11-27 16:58

    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.

    0 讨论(0)
提交回复
热议问题