a blog for those who code

Monday 27 April 2015

[Solved] Bitmap.Clone Out of Memory Exception in C#

In this post we will be discussing about How to solve Out of Memory Exception when we use Bitmap.Clone() in C#. We use Bitmap.Clone() when we have to create a section of the Bitmap defined by Rectangle structure and with a specified PixelFormat enumeration.

According to MSDN, we will get OutOfMemoryException when the rectangle is outside of the source bitmap bounds. In simple terms Rectangle.Height + Rectangle.Y is bigger than Height of the image or Rectangle.Width + Rectangle.X is bigger than Width of the image. So when you change the rectangle X, Y, Height or Width, make sure that it should be less than the height or width or the original image.

If the above solution does not fix your problem, then try the below scenario. Lets suppose you have the following code to crop an image.

function cropImage(Bitmap img, Rectangle cropArea) {
    var image= img.Clone(cropArea, img.PixelFormat);
    return image;

Here we are taking the original image and then based on the rectangle cropArea, we are cropping the original image. So this line var image= img.Clone(cropArea, img.PixelFormat); will give you Out Of Memory exception. The error Out of Memory exception by this line is common when you try to crop large images. To fix this issue you can change the above code to

function cropImage(Bitmap img, Rectangle cropArea) {
    Bitmap bmp = new Bitmap(cropArea.Width, cropArea.Height);
    using(Graphics gph = Graphics.FromImage(bmp))
        gph.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), cropArea, GraphicsUnit.Pixel);
    return bmp;

In the above code we are at first creating a new bitmap image of height and width same as that of the cropArea rectangle (Bitmap bmp = new Bitmap(cropArea.Width, cropArea.Height);).  Using Graphics class we are creating a new graphics by the bmp created in the above line Graphics.FromImage(bmp). Then drawing an image using gph.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), cropArea, GraphicsUnit.Pixel);.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment