2011-03-27 20 views
0

我需要用文件流創建位圖。到目前爲止,我有這個代碼:用文件流創建位圖

using (FileStream bmp = File.Create(@"C:\test.bmp")) 
     { 
      BinaryWriter writer = new BinaryWriter(bmp); 
      int i = 0; 

      // writer.Write((char*)&fileheader, sizeof(fileheader)); 
      // writer.Write((char*)&infoheader, sizeof(infoheader)); 

      for (int rows = 0; rows < 160; rows++) 
      { 
       for (int cols = 0; cols < 112; cols++) 
       { 
        writer.Write(CamData[i]); 
        i++; 
       } 
      } 

      bmp.Close(); 
     } 

但我仍然需要頭位置信息的位圖。我的問題是,我不知道如何在C#中實現它們。我知道分辨率(320 x 240),我的像素數據是在ushort數組中給出的16位灰度值。

感謝

回答

0

有一個構造函數來創建從字節數組Bitmap。然後,使用Bitmap的成員函數將它保存爲bmp格式的流。見herehere

+0

我不能使用Bitmap類,因爲我沒有一個字節數組!我有USHORT值 – h0ppel 2011-03-27 13:52:59

+3

使用Bitmap.LockBits()並要求16bpp格式。 – 2011-03-27 14:52:30

+1

當我使用PixelFormat.Format16bppGrayScale時,我總是得到一個gdi +錯誤。其他像素格式運行良好。使用PixelFormat.Format24bppRgb後,我得到這樣的結果:圖片在第一行3次![test.bmp] [1] [1]:http://i.imgur.com/Cls1e.png – h0ppel 2011-03-27 15:39:59

-1

嘗試這種情況:

/// From stream to bitmap... 
FileStream fs = new FileStream("test.bmp", FileMode.Open); 
Bitmap bmp = new Bitmap(fs); 
+0

但我不想打開現有的位圖。我想用filestream創建一個新的位圖 – h0ppel 2011-03-27 14:24:05

+0

@Klaus將FileMode更改爲FileMode.Create(或任何其他合適的選擇)。無論如何,我想知道如果fs.Close();可以在上面兩行之後立即發佈,或者只要位圖被使用,流是否應該保持打開狀態。 – ADTC 2012-03-06 15:40:27

0

似乎System.Drawing中的類不喜歡處理16位灰度,可能是因爲底層的GDI +對象認爲其顏色成分爲從0到255的值,而16比特灰度級實際上意味着你可以擁有65535個灰色陰影。

這意味着您有兩種選擇:切換到PresentationCore並使用它創建圖像,或者將值縮減爲字節大小並製作8位灰度圖像。

第一個選項在this answer中進行了說明。

第二個選項包括三個步驟:

  • 數據縮減像素採樣到每像素1個字節
  • 生成灰度顏色調色板(因爲8比特灰度級在技術上是調色板)
  • 創建8- bit索引的圖像出你的下采樣數據和調色板。

的代碼:

Byte[] camDataBytes = new Byte[CamData.Length]; 
for(Int32 i = 0; i < camData.Length; i++) 
    camDataBytes[i] = (Byte)(CamData[i]/256); 

Color[] palette = new Color[256]; 
for(Int32 i = 0; i < 256; i++) 
    palette[i] = Color.FromArgb(i,i,i); 

using(Bitmap b = BuildImage(camDataBytes, 320, 240, 320, PixelFormat.Format8bppIndexed, palette, null)) 
    b.Save(@"C:\test.bmp", ImageFormat.Bmp); 

BuildImage函數來創建的圖像出一個字節數組的可以發現here。假設圖像數據是緊湊的320x240,最終的字節數組的步幅應該完全是寬度,因此320.