/// <summary>
/// 使用byte[]資料,產生256色灰階 BMP 位元影像
/// </summary>
/// <param name="originalImageData"></param>
/// <param name="originalWidth"></param>
/// <param name="originalHeight"></param>
/// <returns></returns>
public static Bitmap CreateBitmap(byte[] originalImageData, int originalWidth, int originalHeight)
{
//指定8位格式,即256色
Bitmap resultBitmap = new Bitmap(originalWidth, originalHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
//將該位元影像存入記憶體中
MemoryStream curImageStream = new MemoryStream();
resultBitmap.Save(curImageStream, System.Drawing.Imaging.ImageFormat.Bmp);
curImageStream.Flush();
//由於位元影像資料需要DWORD對齊(4byte倍數),計算需要補位的個數
int curPadNum = ((originalWidth * 8 + 31) / 32 * 4) - originalWidth;
//最終產生的位元影像資料大小
int bitmapDataSize = ((originalWidth * 8 + 31) / 32 * 4) * originalHeight;
//資料部分相對檔案開始位移,具體可以參考位元影像檔案格式
int dataOffset = ReadData(curImageStream, 10, 4);
//改變調色盤,因為預設的調色盤是32位彩色的,需要修改為256色的調色盤
int paletteStart = 54;
int paletteEnd = dataOffset;
int color = 0;
for (int i = paletteStart; i < paletteEnd; i += 4)
{
byte[] tempColor = new byte[4];
tempColor[0] = (byte)color;
tempColor[1] = (byte)color;
tempColor[2] = (byte)color;
tempColor[3] = (byte)0;
color++;
curImageStream.Position = i;
curImageStream.Write(tempColor, 0, 4);
}
//最終產生的位元影像資料,以及大小,高度沒有變,寬度需要調整
byte[] destImageData = new byte[bitmapDataSize];
int destWidth = originalWidth + curPadNum;
//產生最終的位元影像資料,注意的是,位元影像資料 從左至右,從下到上,所以需要顛倒
for (int originalRowIndex = originalHeight - 1; originalRowIndex >= 0; originalRowIndex--)
{
int destRowIndex = originalHeight - originalRowIndex - 1;
for (int dataIndex = 0; dataIndex < originalWidth; dataIndex++)
{
//同時還要注意,新的位元影像資料的寬度已經變化destWidth,否則會產生錯位
destImageData[destRowIndex * destWidth + dataIndex] = originalImageData[originalRowIndex * originalWidth + dataIndex];
}
}
//將流的Position移到資料區段
curImageStream.Position = dataOffset;
//將新位元影像資料寫入記憶體中
curImageStream.Write(destImageData, 0, bitmapDataSize);
curImageStream.Flush();
//將記憶體中的位元影像寫入Bitmap對象
resultBitmap = new Bitmap(curImageStream);
return resultBitmap;
}
/// <summary>
/// 從記憶體流中指定位置,讀取資料
/// </summary>
/// <param name="curStream"></param>
/// <param name="startPosition"></param>
/// <param name="length"></param>
/// <returns></returns>
public static int ReadData(MemoryStream curStream, int startPosition, int length)
{
int result = -1;
byte[] tempData = new byte[length];
curStream.Position = startPosition;
curStream.Read(tempData, 0, length);
result = BitConverter.ToInt32(tempData, 0);
return result;
}
/// <summary>
/// 向記憶體流中指定位置,寫入資料
/// </summary>
/// <param name="curStream"></param>
/// <param name="startPosition"></param>
/// <param name="length"></param>
/// <param name="value"></param>
public static void WriteData(MemoryStream curStream, int startPosition, int length, int value)
{
curStream.Position = startPosition;
curStream.Write(BitConverter.GetBytes(value), 0, length);
}