1

I am getting a System.OutOfMemoryException when I try storing a portions of an image to a bitmap using a loop. I do not think it's because the image is too big because another version of my code uses multiple of the same image but without a bitmap. Here is what I got:

Bitmap map = new Bitmap(img);

for (int i = 0; i < 4; i++) {
    for (int y = 0; y < 4; y++) {
        // Clone a portion of the Bitmap object.
        Rectangle rec = new Rectangle(i*(img.Width / 4), 
                                    y*(img.Height / 4),
                                    img.Width,//image width
                                    img.Height);

        PixelFormat format =  map.PixelFormat;
        Bitmap clone = null;
        try {
            clone = map.Clone(rec, format);
        } catch (OutOfMemoryException e) 
0

1 Answer 1

3

It is because your rectangle bounds are not inside the image.

I think you misunderstood the constructor for Rectangle It gets upper left corner (first and second parameter) and width and height of the rectangle. When you set upper left corner inside your bitmap and provide image.Width and image.Height as width and height of the rectangle it will definitely fall outside of bitmap and you will get OutOfMemoryException

Sign up to request clarification or add additional context in comments.

1 Comment

ohhh okay, thanks! So the first who values would be the x and y position of the top left corner then, if say I wanted to start at the top left corner?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.