title: Loading an image from a stream without keeping the stream open
body: <p>Is it possible to use the FromStream method of System.Drawing.Image without having to keep the stream open for the lifetime of the image?</p>
  
  <p>I have an application which loads a bunch of toolbar graphics from resource files, using a combination of <a href="http://msdn.microsoft.com/en-us/library/1kcb3wy4.aspx" rel="noreferrer"><code>Image.FromStream</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx" rel="noreferrer"><code>Assembly.GetManifestResourceStream</code></a>.</p>
  
  <p>The problem I'm having is while this works fine on Windows 7, on Windows XP the application crashes if a user interface element linked to one of these images is disabled. On Windows 7, the image is rendered in grayscale. On XP, it crashes with an out of memory exception.</p>
  
  <p>After a load of hairpulling I have finally traced it to the initial loading of the image. As a matter of course, if I create any object implementing <code>IDisposable</code> that is also destroyed in the same method, I wrap it in a using statement, for example</p>
  
  <pre><code>using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
  {
     image = Image.FromStream(resourceStream);
  }
  </code></pre>
  
  <p>If I remove the using statement so that the stream isn't disposed, then the application no longer crashes on XP. But I now have a bunch of "orphan" streams hanging about - the images are stored in command classes and these correctly dispose of the images when they themselves are disposed, but the original stream isn't.</p>
  
  <p>I checked the documentation for <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms535371%28v=vs.85%29.aspx" rel="noreferrer"><code>FromStream</code></a> and it confirms the stream needs to remain open. Why this hasn't crashed and burned on the Windows 7 development system is a mystery however!</p>
  
  <p>I really don't want this stream hanging around, and I certainly don't want to have to store a reference to this stream as well as the image so I can dispose of it later. I only have need of that stream once so I want to get rid of it :)</p>
  
  <p>Is it possible to create the image and then kill of the stream there and then?</p>