C# Image 、 byte[] 、Bitmap之间的转化
一、Byte[] 轉(zhuǎn) System.Drawing.Bitmap
public static Bitmap CreateBitmap(byte[] originalImageData, int originalWidth, int originalHeight)
{
//指定8位格式,即256色
Bitmap resultBitmap = new Bitmap(originalWidth, originalHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
//將該位圖存入內(nèi)存中
MemoryStream curImageStream = new MemoryStream();
resultBitmap.Save(curImageStream, System.Drawing.Imaging.ImageFormat.Bmp);
curImageStream.Flush();
//由于位圖數(shù)據(jù)需要DWORD對(duì)齊(4byte倍數(shù)),計(jì)算需要補(bǔ)位的個(gè)數(shù)
int curPadNum = ((originalWidth * 8 + 31) / 32 * 4) - originalWidth;
//最終生成的位圖數(shù)據(jù)大小
int bitmapDataSize = ((originalWidth * 8 + 31) / 32 * 4) * originalHeight;
//數(shù)據(jù)部分相對(duì)文件開(kāi)始偏移,具體可以參考位圖文件格式
int dataOffset = ReadData(curImageStream, 10, 4);
//改變調(diào)色板,因?yàn)槟J(rèn)的調(diào)色板是32位彩色的,需要修改為256色的調(diào)色板
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);
}
//最終生成的位圖數(shù)據(jù),以及大小,高度沒(méi)有變,寬度需要調(diào)整
byte[] destImageData = new byte[bitmapDataSize];
int destWidth = originalWidth + curPadNum;
//生成最終的位圖數(shù)據(jù),注意的是,位圖數(shù)據(jù) 從左到右,從下到上,所以需要顛倒
for (int originalRowIndex = originalHeight - 1; originalRowIndex >= 0; originalRowIndex--)
{
int destRowIndex = originalHeight - originalRowIndex - 1;
for (int dataIndex = 0; dataIndex < originalWidth; dataIndex++)
{
//同時(shí)還要注意,新的位圖數(shù)據(jù)的寬度已經(jīng)變化destWidth,否則會(huì)產(chǎn)生錯(cuò)位
destImageData[destRowIndex * destWidth + dataIndex] = originalImageData[originalRowIndex * originalWidth + dataIndex];
??}
}
//將流的Position移到數(shù)據(jù)段
curImageStream.Position = dataOffset;
//將新位圖數(shù)據(jù)寫入內(nèi)存中
curImageStream.Write(destImageData, 0, bitmapDataSize);
curImageStream.Flush();
//將內(nèi)存中的位圖寫入Bitmap對(duì)象
resultBitmap = new Bitmap(curImageStream);
return resultBitmap;
}
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;
}
轉(zhuǎn)載于:https://www.cnblogs.com/alsofly/p/3373833.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的C# Image 、 byte[] 、Bitmap之间的转化的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 大话设计模式--职责连模式 Chain
- 下一篇: rpm命令用法