开发者

Exception on traveling through pixels BMP C#

Im using the following code to travel though the pixels of a BMP as this

Exception on traveling through pixels BMP C#

for (int i = 0; i <= Image.Width; i++)
 {
    for (int j = 0; j <= Image.Height; j++)
    {
              color = Image.GetPixel(i, j); //get 
    }

 }

but im getting a exception

System.ArgumentOutOfRangeException was unhandled
  开发者_运维百科Message="Parameter must be positive and < Height.\r\nParameter name: y"
  Source="System.Drawing"
  ParamName="y"

I have no clue why im getting this.. im using a BMP with valid heights and same code with hard-coded values working correctly

@Odded

No:1 Shows what i needed and no 2 is whats happening with ur code any idea?

Exception on traveling through pixels BMP C#


Just change Height and Width. This is such an example of looking too far in your own code - this brings back so many memories..

for(int i=0;i<BMP.Height;i++)
{
   for(int j=0;j<BMP.Width;j++)
   {
      color = BMP.GetPixel(j,i);    
   }
}


You have an off-by-one error in your loops.

If the image Height and Width is 100, to get the "last" pixel you will need to call it as GetPixel(99,99).

for (int i = 0; i < Image.Width; i++)
 {
    for (int j = 0; j < Image.Height; j++)
    {
              color = Image.GetPixel(i, j); //get 
    }

 }


Swap the two loops.

for(int j=0; j<BMP.Height; j++)
{
   for(int i=0; i<BMP.Width; i++)
   {
      color = BMP.GetPixel(i,j);     
   }
}

Everyone is focusing on width and height, that's NOT the solution. GetPixel takes two arguments, x and y. The y coordinate must be the outer loop to get the order you want.

The x-coordinate always runs from 0 ... Width-1


Flip your loops around. The outer loop should be the height and the inner loop should be the width if you want it to behave like the 1st image.


Just swap around the Width and Height:

for(int i=0;i<BMP.Height;i++){

   for(int j=0;j<BMP.Width;j++){
      color=BMP.GetPixel(j, i);
   }
}

I've also swapped around i and j so that GetPixel works correctly


Let's make this simple and use x and y instead of i and j so it's easier to think about in Cartesian coordinates.

//For each height, loop through all pixels at that height.
for(int y=0; y < BMP.Height; y++)
{
    for(int x=0; x < BMP.Width; x++)
    {
        color = BMP.GetPixel(x,y);     
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜