C# System.Drawing.Bitmap 克隆时抛出内存不足异常

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

我有一张位图图像,我正尝试将其克隆如下:

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

有时这一行会抛出类型为 OutOfMemoryException 的异常,因此在克隆之前我想确保在 Rectangle 中指定的坐标不在位图的边界之外,因为据我所知,Clone() 也可能抛出内存不足异常。

我知道我可以通过以下方式获得图像的边界:

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

但我不知道如何与 Rectanble 边界进行比较。

有什么办法吗?

最后我做了以下(感谢 Alex K. 的建议):

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);
}