2012-11-28 66 views
1

我必須將位圖的像素轉換爲短陣列。因此,我想:將位圖像素轉換爲字節數組失敗

  • 得到字節
  • 將字節轉換到短

這是我的源獲得字節:

public byte[] BitmapToByte(Bitmap source) 
{ 
    using (var memoryStream = new MemoryStream()) 
    { 
     source.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp); 
     return memoryStream.ToArray(); 
    } 
} 

這不是返回預期結果。還有另一種轉換數據的方式嗎?

+2

'512 x 512 x 4 = 1048576'那麼丟失的字節在哪裏? – leppie

回答

7

請正確解釋您的問題。 「我缺少字節」不是可以解決的問題。你期望什麼數據,你看到了什麼?

Bitmap.Save()將根據指定的格式返回數據,這些格式在所有情況下都不僅包含像素數據(描述寬度和高度的標題,顏色/調色板數據等)。如果你只想像素數據的數組,你Bimap.LockBits()最好看看:

Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg"); 

// Lock the bitmap's bits. 
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); 

// Get the address of the first line. 
IntPtr ptr = bmpData.Scan0; 

// Declare an array to hold the bytes of the bitmap. 
int bytes = Math.Abs(bmpData.Stride) * bmp.Height; 
byte[] rgbValues = new byte[bytes]; 

// Copy the RGB values into the array. 
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); 

現在rgbValues數組包含從源位圖的所有像素,每個像素使用3個字節。我不知道你爲什麼想要一些短褲,但你必須能夠從這裏弄清楚。

+2

+1,從來不知道'Stride'可能是負的,P – leppie

+1

@leppie我沒有,但[_」如果步幅是肯定的,位圖是自上而下如果步幅是否定的,位圖是自下而上的。 「_](http://msdn.microsoft.com/en-us/library/system.drawing.imaging.bitmapdata.stride.aspx)。 – CodeCaster

+0

我現在必須使用整數值,但最終沒有區別。謝謝 – Goot

相關問題