Creating WPF BitmapImage from MemoryStream png, gif

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))
{
   ...
}

Leave a Comment