C# 如何重置捕获像素的值

C# 如何重置捕获像素的值,c#,screenshot,rgb,pixel,C#,Screenshot,Rgb,Pixel,我正在尝试制作一个C#函数,从截图位图中返回每四个像素的R、G和B值。这是我代码的一部分 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 = screen

我正在尝试制作一个C#函数,从截图位图中返回每四个像素的R、G和B值。这是我代码的一部分

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;                
    }
}
for(int-ix=4;ix<1366;ix=ix+4)
{
x=x+4;
对于(int-iy=3;iy<768;iy=iy+4)
{
y=y+4;
System.Drawing.Color pixelcolor=screenshot.GetPixel(x,y);
红色=kolorpiksela.R;
绿色=kolorpiksela.G;
蓝色=kolorpiksela.B;
sumR=sumR+红色;
sumG=sumG+绿色;
sumB=sumB+蓝色;
}
}
其中
屏幕截图
是位图。最后,将“总和”值除以像素数。我的问题是它不起作用。我得到的错误是:

System.Drawing.dll中发生类型为“System.ArgumentOutOfRangeException”的未处理异常

附加信息:参数必须为正值且<高度


我认为错误的原因是,
pixelcolor
每一步都应该重置,但我在过去的两天里一直在尝试重置。没有成功。

我只是不知道这里发生了什么:

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

    for (int iy = 3; iy < 768; iy = iy + 4)
    {
        y = y + 4;
for(int-ix=4;ix<1366;ix=ix+4)
{
x=x+4;
对于(int-iy=3;iy<768;iy=iy+4)
{
y=y+4;
我猜应该是这样的:

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);
for(int x=0;x

在不需要的时候,尽量不要硬键入值。我甚至可能会将“4”转换为常量或某个属性。

我假设您的位图是1366 x 768

在您的ix循环中,在第一次迭代中ix=4。在第431次迭代中ix=1364,因此它进入循环

问题是,然后将4添加到超过1366边界的x(因此x=1368)

硬编码位图尺寸并不是最好的方法,但您可以快速检查x=x+4是否超过1366边界

768的iy循环也差不多。

试试这个:

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;
    }
}
for(int x=0;x
位图的大小是多少?