2013-03-08 19 views
2

我有一個關於C#中的一些基於像素的操作的問題。 我寫了一個類,作爲一個Bitmap周圍的圖像殼。它可以通過使用BitmapDataLockBits來獲得圖像中特定(x,y)位置處像素的RGB值,其速度比顏色對象的顏色快得多,可以直接訪問圖像數組並從中讀取字節。我添加了這個函數來獲取(x,y)像素處的0x00RRGGBB蒙板中的RGB。C#中MSpaint圖像的圖像跨度是+1字節,爲什麼?

public unsafe int getPixel(int x, int y) 
    { 
     byte* imgPointer = (byte*)bmpData.Scan0; 
     int pixelPos = 0; 
     if (y > 0) pixelPos += (y * bmpData.Stride); 
     pixelPos += x * (hasAlpha ? 4 : 3);    

     int blue = *(imgPointer + pixelPos); 
     int green = *(imgPointer + pixelPos + 1); 
     int red = *(imgPointer + pixelPos + 2); 

     int rgb = red << 16; 
     rgb += green << 8; 
     rgb += blue; 

     return rgb; 
    } 

這完美的作品對我的一切,因此到目前爲止的工作,除了我生成使用MSPAINT任何圖像的圖像。例如,我在包含5個黃色陰影的塗料中製作了5x1圖像。但是,當我將這個圖像加載到我的程序中時,圖像跨度爲16!我懷疑它是15(每個像素3個字節,5個像素),但由於某些原因,在前三個字節(第一個像素)之後有一個額外的字節,然後其餘的像素在數組中。

我只發現了MSpaint保存的圖像,我希望任何人都可以解釋我額外的字節是什麼,以及如何檢測額外的字節。

回答

3

MSDN

The stride is the width of a single row of pixels (a scan line), rounded up to a four-byte boundary. If the stride is positive, the bitmap is top-down. If the stride is negative, the bitmap is bottom-up.

所以步幅始終是4的倍數,併爲您的3x5的,將全面達16