-2

i'm trying to store pixel values of an image into 2-d array using getpixel method when the for loop reach [0,240] i get outofrange exception any one can help me ?

  // Loop through the images pixels to store in array. 
                for (x = 0; x < image1.Height; x++)
                {
                    for (y = 0; y < image1.Width; y++)
                    {
                       Color p = ((Bitmap)image1).GetPixel(x, y);
                         pic[x,y] = p.ToString();
                    }
                }
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

1 Answers1

1

You are looping x as the height and y as width, but then you use them the other way to access the pixels.

Loop x as width and y as height:

// Loop through the images pixels to store in array. 
            for (y = 0; y < image1.Height; y++)
            {
                for (x = 0; x < image1.Width; x++)
                {
                   Color p = ((Bitmap)image1).GetPixel(x, y);
                     pic[x,y] = p.ToString();
                }
            }
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Although I suspect he wants to do `pic[y,x] = p.ToString();` Because his array is likely addressed by `row, col` and the pixels are addressed by `col, row`. I guess it depends on whether he defined his array as `[width, height]` or `[height, width]`. – Jim Mischel Jan 10 '15 at 17:30
  • @JimMischel: Yes that's possible, but the most likely reason for the out of range expection is that the array is declared as `[width, height]`. If the array was large enouth the original code would give an `ArgumentOutOfRangeException` when the `GetPixel` tried to read outside the image. – Guffa Jan 10 '15 at 17:51
  • OK Mr Guffa I used your loop and it works just fine thank you for your help . – nada hussien Jan 11 '15 at 18:29
  • @nadahussien: If his response solved your problem, you should mark the answer as accepted (click the check mark to the left of the answer). – Jim Mischel Jan 16 '15 at 17:04