在 .NET 開發中,將原始位元組資料流轉換為 Bitmap 物件是常見需求。核心原理在於將資料序列化至記憶體流,加入 BMP 格式所需的檔案標頭,再反序列化為圖片物件。最大的挑戰在於正確構建這 14 位元組的標頭資訊。
BMP 標頭包含固定的 14 位元組:前兩位元組為 0x42、0x4D(ASCII "BM"),接著 4 位元組記錄檔案總大小,再 4 位元組保留值(通常為 0),最後 4 位元組指向像素資料的起始位移(標準為 0x36)。這段標頭對所有 Bitmap 通用,因此可封裝為可重用方法。
using System;
using System.Drawing;
using System.IO;
public Bitmap AddHeader(byte[] imageDataDetails)
{
Bitmap bitmap = null;
int length = imageDataDetails.Length;
using (MemoryStream stream = new MemoryStream(length + 14))
{
byte[] buffer = new byte[14];
buffer[0] = 0x42; // 'B'
buffer[1] = 0x4D; // 'M'
// 檔案大小(含標頭)
byte[] fileSizeBytes = BitConverter.GetBytes(length + 14);
Array.Copy(fileSizeBytes, 0, buffer, 2, 4);
// 保留欄位(4 bytes,全 0)
// 像素資料起始位移
byte[] offsetBytes = BitConverter.GetBytes(0x36);
Array.Copy(offsetBytes, 0, buffer, 10, 4);
stream.Write(buffer, 0, 14);
stream.Write(imageDataDetails, 0, length);
bitmap = new Bitmap(stream);
bitmap.RotateFlip(RotateFlipType.Rotate180FlipX); // 依影像方向調整
}
return bitmap;
}
length + 14 避免擴容開銷。using 區塊確保串流正確關閉。若需將 Bitmap 存回資料庫或傳輸,可用 ImageConverter 或手動移除標頭後寫入 MemoryStream,再取得 ToArray() 結果。
掌握此技巧,即可靈活處理影像上傳、截圖、報表匯出等場景,提升系統整合彈性。