Creating WPF BitmapImage from MemoryStream png, gif

后端 未结 2 1294
星月不相逢
星月不相逢 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))
    {
       ...
    }
    

提交回复
热议问题