Home > Blockchain >  How to get the number of pixels of image?
How to get the number of pixels of image?

Time:10-05

private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
        {
            Bitmap rectImage = cropAtRect((Bitmap)pictureBox2.Image, rect);

            int x, y;

            for (x = rect.X; x < rect.Width; x  )       {
                for (y = rect.Y; y < rect.Height; y  )           {
                    Color pixelColor = rectImage.GetPixel(x, y);
                    pixelsCounter  ;
                }
            }

            pictureBox1.Image = rectImage;
        }

i want to get the number of pixels in rectImage. i can see the rectImage in pictureBox1 but the variable pixelsCounter is 0 after the loops.

CodePudding user response:

Let's say you have a rectangle that goes from X-coordinate 10 (inclusive) to X-coordinate 15 (exclusive):

          xxxxx
012345678901234567890

Obviously, this rectangle is 5 pixels wide, i.e. rect.Width will be 5. Let's have a look at your loop:

for (x = rect.X; x < rect.Width; x  )

This loop will start at X (10) and increase the loop counter until it reaches Width (5). You see how this is bound to fail?

You need to either loop from 10 to 15 (i.e. from X to X Width) or from 0 to 5 (i.e. from 0 to Width). Which one is the right one depends on what you intend to do with the loop index.

In your case, however, you don't need the loop as all. As mentioned in the comments, the number of pixels is simply Width * Height.

  • Related