T.Brown
T.Brown

Reputation: 89

Bitmap manipulation throwing System.ArgumentOutOfRangeException

I'm trying to write a piece of code to create a black bitmap

Bitmap rectangle = new Bitmap(100, 100);
for (int i = 1; i <= rectangle.Width - 1; i++)
    for (int j = 1; i <= rectangle.Height - 1; j++)
        rectangle.SetPixel(i, j, Color.Black);

But it keeps throwing System.ArgumentOutOfRangeException.

Upvotes: 1

Views: 85

Answers (1)

Trauer
Trauer

Reputation: 2091

Bitmap rectangle = new Bitmap(100, 100);
for (int i = 1; i <= rectangle.Width - 1; i++)
    for (int j = 1; i <= rectangle.Height - 1; j++)
        rectangle.SetPixel(i, j, Color.Black);

The problem is in your second loop's stoping condition:

 i <= rectangle.Height - 1

should be

 j <= rectangle.Height - 1

I now this isn't a 'code review' question, but here's a suggestion: avoid using magic numbers We can do this simply removing -1 and using < instead of <=.

Bitmap rectangle = new Bitmap(100, 100);
for (int i = 0; i < rectangle.Width; i++)
    for (int j = 0; j < rectangle.Height; j++)
        rectangle.SetPixel(i, j, Color.Black);

Upvotes: 1

Related Questions