簡體   English   中英

如何在C#中使用帶偏移的2D點獲取數組的索引

[英]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的順序排列,我們可以像“掃描”中那樣組織它們:

第一次掃描:

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

例如,如何獲取點(2,3)的藍色字節的索引?

PS:這是我在這里的第一個問題,對於可能會犯的任何錯誤,我事先表示歉意,我將學習!

如果您不太關心性能:

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

好的,我找到了解決問題的答案,而從2D陣列轉換為1D的方法對我有所幫助。

但是,由於我需要使用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 point width是數組的寬度(我是通過計算BitmapData Stride來計算數組的大小時得到的) 通道的值,紅色為0,綠色為1,藍色為2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM