/// <summary>
/// 使用byte[]数据生成色灰度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)
{
//指定位格式即色
Bitmap resultBitmap = new Bitmap(originalWidth originalHeight SystemDrawingImagingPixelFormatFormatbppIndexed);
//将该位图存入内存中
MemoryStream curImageStream = new MemoryStream();
resultBitmapSave(curImageStream SystemDrawingImagingImageFormatBmp);
curImageStreamFlush();
//由于位图数据需要DWORD对齐(byte倍数)计算需要补位的个数
int curPadNum = ((originalWidth * + ) / * ) originalWidth;
//最终生成的位图数据大小
int bitmapDataSize = ((originalWidth * + ) / * ) * originalHeight;
//数据部分相对文件开始偏移具体可以参考位图文件格式
int dataOffset = ReadData(curImageStream );
//改变调色板因为默认的调色板是位彩色的需要修改为色的调色板
int paletteStart = ;
int paletteEnd = dataOffset;
int color = ;
for (int i = paletteStart; i < paletteEnd; i += )
{
byte[] tempColor = new byte[];
tempColor[] = (byte)color;
tempColor[] = (byte)color;
tempColor[] = (byte)color;
tempColor[] = (byte);
color++;
curImageStreamPosition = i;
curImageStreamWrite(tempColor );
}
//最终生成的位图数据以及大小高度没有变宽度需要调整
byte[] destImageData = new byte[bitmapDataSize];
int destWidth = originalWidth + curPadNum;
//生成最终的位图数据注意的是位图数据 从左到右从下到上所以需要颠倒
for (int originalRowIndex = originalHeight ; originalRowIndex >= ; originalRowIndex)
{
int destRowIndex = originalHeight originalRowIndex ;
for (int dataIndex = ; dataIndex < originalWidth; dataIndex++)
{
//同时还要注意新的位图数据的宽度已经变化destWidth否则会产生错位
destImageData[destRowIndex * destWidth + dataIndex] = originalImageData[originalRowIndex * originalWidth + dataIndex];
}
}
//将流的Position移到数据段
curImageStreamPosition = dataOffset;
//将新位图数据写入内存中
curImageStreamWrite(destImageData bitmapDataSize);
curImageStreamFlush();
//将内存中的位图写入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 = ;
byte[] tempData = new byte[length];
curStreamPosition = startPosition;
curStreamRead(tempData length);
result = BitConverterToInt(tempData );
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)
{
curStreamPosition = startPosition;
curStreamWrite(BitConverterGetBytes(value) length);
}