简体   繁体   中英

How to reset value of captured pixel

I'm trying to make a C# function that returns the R, G and B values of every fourth pixel from a screenshot bitmap. This is part of my code.

for (int ix = 4; ix < 1366; ix = ix + 4)
{
    x = x + 4;

    for (int iy = 3; iy < 768; iy = iy + 4)
    {
        y = y + 4;

        System.Drawing.Color pixelcolor = screenshot.GetPixel(x,y);
        red = kolorpiksela.R;
        green = kolorpiksela.G;
        blue = kolorpiksela.B;

        sumR = sumR + red;
        sumG = sumG + green;
        sumB = sumB + blue;                
    }
}

Where screenshot is a bitmap. At the end the "sums" values are divided by the number of pixels. My problem is that it doesn't work. The error I get is:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Drawing.dll

Additional information: Parameter must be positive and < Height.

I think the reason for the error is that pixelcolor should be reset every step, but I tried to do that for the last 2 days. No success.

I just don't know what's going on here:

for (int ix = 4; ix < 1366; ix = ix +4 )
{
    x = x + 4;

    for (int iy = 3; iy < 768; iy = iy + 4)
    {
        y = y + 4;

My guess would be that it should look like:

for (int x = 0; x < screenshot.Width; x += 4 )
{
    for (int y = 0; y < screenshot.Height; y += 4)
    {
        System.Drawing.Color pixelcolor = screenshot.GetPixel(x,y);

Try to never hard type values when you don't have to. I would probably even turn that "4" into a const or a property somewhere.

I'm assuming your Bitmap is 1366 x 768.

In your ix loop, on the 1st iteration ix = 4. On the 431st itteration ix = 1364, so it goes in the loop.

The problem is you then add 4 to x (so x = 1368) which exceeds your 1366 boundry.

Hardcoding your bitmap dimensions isn't the best way, but you could put a quick if check in to see if x = x + 4 exceeds your 1366 boundary.

Pretty much the same thing for your iy loop for the 768.

Try this:

for (int x = 0; x < screenshot.Width; x += 4)
{
    for (int y = 0; y < screenshot.Height; y += 4)
    {
        Color pixelcolor = screenshot.GetPixel(x, y);
        sumR += pixelcolor.R;
        sumG += pixelcolor.G;
        sumB += pixelcolor.B;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM