Search code examples
c#bitmapsystem.drawing

C# System.Drawing.Bitmap throwing Out of Memory Exception when cloning


I have a Bitmap image which I am trying to clone as below:

Bitmap bmpCrop = bmp.Clone(new System.Drawing.Rectangle(left, top, right - left + 1, bottom - top), bmp.PixelFormat);

Sometimes this line throws an exception of type OutOfMemoryException so previously to clone I want to be sure that the coordinates specified in the Rectangle are not outside the bounds of the bitmap since as far as I know, Clone() may also throw an Out of memory exception.

I know I can get the bounds of the image by doing:

GraphicsUnit units = GraphicsUnit.Point;
RectangleF bmpRectangleF = bmp.GetBounds(ref units);

but then I do not know how to comprare with Rectanble bounds.

Is there any way to do it?


Solution

  • Finally I have done below (thanks to Alex K. for the suggestion):

    RectangleF rectangleF = new System.Drawing.Rectangle(left, top, right - left + 1, bottom - top);
    GraphicsUnit units = GraphicsUnit.Pixel;
    RectangleF bmpRectangleF = bmp.GetBounds(ref units);
    if (bmpRectangleF.Contains(rectangleF))
    {
        Bitmap bmpCrop = bmp.Clone(rectangleF, bmp.PixelFormat);
        return (Bitmap)(bmpCrop);
    }