Creating WPF BitmapImage from MemoryStream png, gif

后端 未结 2 1264
星月不相逢
星月不相逢 2020-11-27 04:45

I am having some trouble creating a BitmapImage from a MemoryStream from png and gif bytes obtained from a web request. The bytes seem to be downlo

相关标签:
2条回答
  • 2020-11-27 05:29

    Add bi.CacheOption = BitmapCacheOption.OnLoad directly after your .BeginInit():

    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.CacheOption = BitmapCacheOption.OnLoad;
    ...
    

    Without this, BitmapImage uses lazy initialization by default and stream will be closed by then. In first example you try to read image from possibly garbage-collected closed or even disposed MemoryStream. Second example uses file, which is still available. Also, don't write

    var byteStream = new System.IO.MemoryStream(buffer);
    

    better

    using (MemoryStream byteStream = new MemoryStream(buffer))
    {
       ...
    }
    
    0 讨论(0)
  • 2020-11-27 05:38

    I'm using this code:

    public static BitmapImage GetBitmapImage(byte[] imageBytes)
    {
       var bitmapImage = new BitmapImage();
       bitmapImage.BeginInit();
       bitmapImage.StreamSource = new MemoryStream(imageBytes);
       bitmapImage.EndInit();
       return bitmapImage;
    }
    

    May be you should delete this line:

    bi.DecodePixelWidth = 30;
    
    0 讨论(0)
提交回复
热议问题