2012-04-30 80 views
0

我一直在使用AForge.NET框架開發一個項目。在我的項目中,我一直試圖從灰度位圖獲取二維字節數組。在本網站和其他論壇上發佈了關於此主題的一些解決方案。但是我沒有得到真正的結果。例如,我使用該代碼:在C#中將位圖轉換爲二維字節數組?

public static byte[] ImageToByte2(Image img) 
{ 
    byte[] byteArray = new byte[0]; 
    using (MemoryStream stream = new MemoryStream()) 
    { 
     img.Save(stream, System.Drawing.Imaging.ImageFormat.Png); 
     stream.Close(); 

     byteArray = stream.ToArray(); 
    } 
    return byteArray; 
} 

在此「MemoryStream」方法後,我想過將此字節數組轉換爲2D。但是,當我使用4 * 8位圖測試此代碼示例時,它將1100個值返回到byteArray。這是正常的嗎?我錯過了什麼?

回答

1

.NET Image類可用作兩種類型圖像的接口:Bitmap圖像和Metafile圖像。後者由一系列繪製指令的指令組成,而不是像位圖那樣的像素數組。如果你看看Bitmap class itself,有一對LockBits方法可以讓你提取圖像的像素數據。在Bitmap課程的鏈接參考底部,甚至有一個例子說明了如何做到這一點。

0

,請使用以下方法

public static byte[,] ImageTo2DByteArray(Bitmap bmp) 
    { 
     int width = bmp.Width; 
     int height = bmp.Height; 
     BitmapData data = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); 

     byte[] bytes = new byte[height * data.Stride]; 
     try 
     { 
      Marshal.Copy(data.Scan0, bytes, 0, bytes.Length); 
     } 
     finally 
     { 
      bmp.UnlockBits(data); 
     } 

     byte[,] result = new byte[height, width]; 
     for (int y = 0; y < height; ++y) 
      for (int x = 0; x < width; ++x) 
      { 
       int offset = y * data.Stride + x * 3; 
       result[y, x] = (byte)((bytes[offset + 0] + bytes[offset + 1] + bytes[offset + 2])/3); 
      } 
     return result; 
    }