2012-09-20 95 views
0

我需要閱讀的BMP getpixel與速度,但非常低 我用LockBits改善速度

 private void LockUnlockBitsExample(Bitmap bmp) 
    { 

     Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); 
     System.Drawing.Imaging.BitmapData bmpData = 
      bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, 
      bmp.PixelFormat); 
     IntPtr ptr = bmpData.Scan0; 

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

     System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); 
     bmp.UnlockBits(bmpData); 
    } 

的這個功能

 private Color GetMyPixel(byte[] rgbValues,Bitmap bmp, int x,int y) 
    { 

     int index= (bmp.Width*y+x)*3; 
     Color MyColor = Color.FromArgb(rgbValues[index], rgbValues[index + 1], rgbValues[index + 2]); 
     return MyColor; 
    } 

,但我的函數的輸出是不同於原來的getpixel

+0

什麼是原始圖像的顏色格式的東西嗎?看起來你的GetMyPixel函數假設圖像是每像素24位。 – sam1589914

+0

我的圖像是24位 – jozi

回答

1

我有VB中的代碼,由於某種原因,幾乎完全相同的事情,所以我希望這可以幫助。您可以嘗試對GetMyPixel進行以下修改:

使用Stride而不是Width,並在您調用FromArgb時反轉字節順序。

private Color GetMyPixel(byte[] rgbValues,Bitmap bmp, int x,int y) 
{ 
    int index= (bmp.Stride*y+x*3);   
    if (index > rgbValues.Length - 3) 
    index = rgbValues.Length - 3; 
    Color MyColor = Color.FromArgb(rgbValues[index+2], rgbValues[index + 1], rgbValues[index]);   
    return MyColor; 
} 
2

在這一行:

int index= (bmp.Width*y+x)*3;

我認爲bmp.Stride必須用來代替bmp.Width。還要檢查PixelFormat是每像素24位的假設。

另一件事是顏色索引:藍色是第一個(index),然後是綠色(index+1),然後是紅色(index + 2)。

+0

由於這是公認的答案,我想說,簡單地用bmp.Stride替換bmp.Width將是不正確的,因爲您不希望將步幅乘以y和3(每像素的字節數) 。寬度是長度是像素,所以將其乘以3是正確的,但將步幅乘以3是不正確的。 –

+0

@JasonHermann你是絕對正確的。我不得不錯過了。 –

+0

@JasonHermann坦克發表評論 – jozi