Search code examples
c#directxslimdx

Cannot Clone Bitmap after Stream Disposed


I load a bitmap from a DataStream. I try to return the loaded bitmap from a method, and later use it as a source to clone a new bitmap. Unfortunately, the Clone() call results in an OutOfMemoryException. Through testing I realized that Clone() succeeds until the underlying data stream is disposed.

How can I create a bitmap that exists independent from the stream it was loaded from?

DxScreenCapture cap = new DxScreenCapture();
var surface = cap.CaptureScreen();

Bitmap png;
Rectangle rect;
PixelFormat fmt;
using (DataStream stream = Surface.ToStream(surface, ImageFileFormat.Bmp))
{
    png = new Bitmap(stream);

    fmt = png.PixelFormat;
    rect = new Rectangle(911, 170, 32, 14);

    // Works
    Bitmap rgn1 = png.Clone(rect, fmt);
}
// Throws OutOfMemoryException
Bitmap rgn2 = png.Clone(rect, fmt);

Solution

  • Building on Hans' comment, I simply created a new bitmap from the original one.

    Bitmap copy;
    using (DataStream stream = Surface.ToStream(surface, ImageFileFormat.Bmp))
    {
        Bitmap orig = new Bitmap(stream);
        copy = new Bitmap(orig);
    }
    
    // Able to use copy after stream is disposed