title: Creating WPF BitmapImage from MemoryStream png, gif
body: <p>I am having some trouble creating a <code>BitmapImage</code> from a <code>MemoryStream</code> from png and gif bytes obtained from a web request. The bytes seem to be downloaded fine and the <code>BitmapImage</code> object is created without issue however the image is not actually rendering on my UI. The problem only occurs when the downloaded image is of type png or gif (works fine for jpeg).</p>
  
  <p>Here is code that demonstrates the problem:</p>
  
  <pre><code>var webResponse = webRequest.GetResponse();
  var stream = webResponse.GetResponseStream();
  if (stream.CanRead)
  {
      Byte[] buffer = new Byte[webResponse.ContentLength];
      stream.Read(buffer, 0, buffer.Length);
  
      var byteStream = new System.IO.MemoryStream(buffer);
  
      BitmapImage bi = new BitmapImage();
      bi.BeginInit();
      bi.DecodePixelWidth = 30;
      bi.StreamSource = byteStream;
      bi.EndInit();
  
      byteStream.Close();
      stream.Close();
  
      return bi;
  }
  </code></pre>
  
  <p>To test that the web request was correctly obtaining the bytes I tried the following which saves the bytes to a file on disk and then loads the image using a <code>UriSource</code> rather than a <code>StreamSource</code> and it works for all image types:</p>
  
  <pre><code>var webResponse = webRequest.GetResponse();
  var stream = webResponse.GetResponseStream();
  if (stream.CanRead)
  {
      Byte[] buffer = new Byte[webResponse.ContentLength];
      stream.Read(buffer, 0, buffer.Length);
  
      string fName = "c:\\" + ((Uri)value).Segments.Last();
      System.IO.File.WriteAllBytes(fName, buffer);
  
      BitmapImage bi = new BitmapImage();
      bi.BeginInit();
      bi.DecodePixelWidth = 30;
      bi.UriSource = new Uri(fName);
      bi.EndInit();
  
      stream.Close();
  
      return bi;
  }
  </code></pre>
  
  <p>Anyone got any light to shine?</p>