如何在 C# 中使用带偏移量的二维点获取数组的索引

How to get the index of an array by using a 2D Point with an offset in C#

我目前正在使用 C# 通过 Lockbits 方法从位图中获取像素信息,如下所示:

BitmapData bmpData = bmpFromScreen2.LockBits(
                new Rectangle(0, 0, startDimensions.X, startDimensions.Y),
                ImageLockMode.ReadWrite,
                bmpFromScreen2.PixelFormat);

到目前为止一切顺利,然后,我将 bmpData 复制到字节数组中,如下所示:

            IntPtr ptr = bmpData.Scan0;

            int bytes = Math.Abs(bmpData.Stride) * bmpFromScreen2.Height;
            byte[] rgbValues = new byte[bytes];

            Marshal.Copy(ptr, rgbValues, 0, bytes);

我知道我将以这种方式获取字节:蓝绿红蓝绿红...等等。

现在我的问题来了:我需要使用位图坐标获取特定像素的RGB数据。

例如:

假设我像这样从 9 个像素中获取 rgbValues:

255, 255, 0, 120, 222, 230, 15, 255, 0, 130, 255, 140, 50, 20, 20, 25, 115, 210, 170, 0, 0, 45, 50, 100, 90, 75, 120.

让(也)假设这 9 个像素按 3x3 的顺序排列,我们可以像 "scans":

那样组织它们

第一次扫描:

255, 255, 0, 120, 222, 230, 15, 255, 0

第二次扫描:

130, 255, 140, 50, 20, 20, 25, 115, 210

第三次扫描:

170, 0, 0, 45, 50, 100, 90, 75, 120

比如Point(2,3)的Blue byte的索引如何获取?

P.S这是我的第一个问题,如有错误请见谅,我会学习的!

如果您不太关心性能:

Color pixelColor = bmpFromScreen2.GetPixel(x,y);

好的,我找到了问题的答案,帮助我的是从二维数组转换为一维数组。

但是,由于我需要使用 3 的偏移量(因为数据为每个像素存储了 3 个值,并且还考虑到我需要从第一个通道的参考中获取另外两个通道,所以我想出了使用此方法:

public static byte GetIndexValue(byte[] array, Point point, int width, int channel)
        {
            int indexLoc = point.X + 3 + channel + point.Y * width;

            byte indexValue = array[indexLoc];

            return indexValue;
        }

其中: array显然是存放BitmapData的字节数组。 point 是 2D X,Y 点 width 是数组的宽度(这是我通过使用 BitmapData Stride 计算数组大小时得到的) 通道 红色值为 0,绿色值为 1,蓝色值为 2