2013-08-02 21 views
1

我想寫一個代碼,爲位圖文件中的每個像素提取像素顏色值。爲此目的,我將bmp導入爲位圖對象,並使用了Bitmap.GetPixel(x,y)方法,但對於我的應用程序來說速度不夠快。我的一位同事給了我一個建議;我想我可以使用fopen來打開文件本身,將字節數據解析爲一個數組。你們有沒有任何想法?使用fopen方法不是必須的,我可以使用任何東西。位圖到字節[]使用Fo​​pen

在此先感謝。

+0

這並不容易。您需要將不同的格式從原始數據轉換爲目標格式,這並不容易。至少這是我知道多少。您可以使用'byte [] data = System.IO.File.ReadAllBytes('file.bmp')'來獲取您的數據,但我已經談過格式化。 – MahanGM

+0

fopen()函數與FileStream或File.ReadAllBytes()或Image.FromFile()沒有更快或不同。專注於使用不安全的指針,*這是GetPixel()的替代方法。使用Bitmap.LockBits(),那裏有大量的谷歌點擊。 –

回答

2

您可以使用不安全的代碼塊,也可以使用Marshal class。我會這樣解決:

public static byte[] GetBytesWithMarshaling(Bitmap bitmap) 
{ 
    int height = bitmap.Height; 
    int width = bitmap.Width; 

    //PixelFormat.Format24bppRgb => B|G|R => 3 x 1 byte 
    //Lock the image 
    BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); 
    // 3 bytes per pixel 
    int numberOfBytes = width * height * 3; 
    byte[] imageBytes = new byte[numberOfBytes]; 

    //Get the pointer to the first scan line 
    IntPtr sourcePtr = bmpData.Scan0; 
    Marshal.Copy(sourcePtr, imageBytes, 0, numberOfBytes); 

    //Unlock the image 
    bitmap.UnlockBits(bmpData); 

    return imageBytes; 
} 
+0

這是第一個答案,它完美運作。謝謝。但是我無法理解階級元帥是什麼,以及什麼是鎖定方法,請您簡單解釋一下嗎? – talkanat

+1

1,Lockbits =>在對象的生命週期中,它們在內存中的位置可能會改變,例如垃圾收集之後。爲了防止這種行爲,位圖被鎖定/固定在內存中。我認爲它像固定聲明一樣工作。 2,Marshal是一個靜態類,有一堆方法可以在託管和非託管代碼之間進行互操作,分配非託管內存等。 – boli