Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Out of Memory when Creating Bitmap

I'm creating an application (Windows Form) that allows the user to take a screenshot based on the locations they choose (drag to select area). I wanted to add a little "preview pane" thats zoomed in so the user can select the area they want more precisely (larger pixels). On a mousemove event i have a the following code...

private void falseDesktop_MouseMove(object sender, MouseEventArgs e)
    {
        zoomBox.Image = showZoomBox(e.Location);
        zoomBox.Invalidate();
        bmpCrop.Dispose();
    }

private Image showZoomBox(Point curLocation)
    {
        Point start = new Point(curLocation.X - 50, curLocation.Y - 50);
        Size size = new Size(100, 90);
        Rectangle rect = new Rectangle(start, size);
        Image selection = cropImage(falseDesktop.Image, rect);
        return selection;
    }

private static Bitmap bmpCrop;
private static Image cropImage(Image img, Rectangle cropArea)
    {
        if (cropArea.Width != 0 && cropArea.Height != 0)
        {
            Bitmap bmpImage = new Bitmap(img);
            bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
            bmpImage.Dispose();
            return (Image)(bmpCrop);
        }
        return null;
    }

The line that fails and has the Out of Memory exception is:

bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);

Basically what this does is it takes a 100x90 rectangle around the mouse pointer and pulls that into the zoomBox, which is a picturebox control. However, in the process, i get an Out Of Memory error. What is it that i am doing incorrectly here?

Thanks for your assistance.

like image 865
Alex Avatar asked Nov 30 '10 20:11

Alex


3 Answers

Out of memory in C# imaging, is usually sign of wrong rect or point - a bit of red herring. I bet start has negative X or Y when error happens or the Size.Hight + Y or Size.Width + X is bigger than Hight or width of the image.

like image 96
Aliostad Avatar answered Nov 22 '22 11:11

Aliostad


MSDN explains that an OutOfMemoryException means

rect is outside of the source bitmap bounds

where rect is the first parameter to the Bitmap.Clone method.

So check that the cropArea parameter is not larger than your image.

In GDI+ an OutOfMemoryException does not really mean "out of memory"; the GDI+ error code OufOfMemory has been overloaded to mean different things. The reasons for this are historic and a well described by Hans Passant in another answer.

like image 24
Dirk Vollmar Avatar answered Nov 22 '22 10:11

Dirk Vollmar


Use the Bitmap object like this:

using (Bitmap bmpImage = new Bitmap(img))
{
    // Do something with the Bitmap object
}
like image 29
Gilad Pomer Avatar answered Nov 22 '22 10:11

Gilad Pomer