Search code examples
c#bitmapsystem.drawing

Cloning and then cropping an image using System.Drawing.Rectangle returns 'out of memory' exception


I am trying to crop the bottom 25% of an image but I am getting an 'out of memory' exception. I know from testing in my code and research that this exception is purely being thrown due to my coordinates being out of range.

I have an image called bmp which is 400px in width and 250px in height. I am cropping it with the following code...

PixelFormat = bmp.PixelFormat;
Bitmap CroppedImage = bmp.Clone(new System.Drawing.Rectangle(0, 250, 400, 62), bmpFormat);

This gives me: 'Exception Details: System.OutOfMemoryException: Out of memory.'

However, if my code was written...

PixelFormat = bmp.PixelFormat;
Bitmap CroppedImage = bmp.Clone(new System.Drawing.Rectangle(0, 0, 400, 62), bmpFormat);

my image is cropped from the top left downwards (i.e. I am getting the top 25%) which to me makes no sense to me as surely I would need to have the height set as -62 not 62 to do this.

If somebody could point me towards an answer on this that would be superb!


Solution

  • Bear in mind that first two arguments in Rectangle's constructor are coordinates of the upper left corner of the rectangle. This makes rectangle's upper right corner being at (650, 0) going over image's 400 width in your first example. Therefore exception.

    In your second example, rectangle covers original image along its width but its height is only 62 pixels - therefore you see only that upper part of the image cropped.

    Also, note that y axis is not placed like in classical geometry. Here y axis points "down".