C# byte數組轉換爲8bit灰度圖像的問題類似的文章在網上可以看到不少,但多多少少都存在一些問題。這兩天做實驗室的項目用到這個功能,我從頭把它整理了一遍。在看代碼之前,首先解釋幾個問題。
1、byte數組存放的是圖像每個像素的灰度值,byte類型正好是從0~255,存放8bit灰度圖像的時候,一個數組元素就是一個像素的灰度值。僅有這個數組還不足以恢復出原來的圖像,還必須事先知道圖像的長、寬值;
2、創建Bitmap類的時候必須指定PixelFormat爲Format8bppIndexed,這樣才最符合圖像本身的特性;
3、Bitmap類雖然提供了GetPixel()、SetPixel()這樣的方法,但我們絕對不能用這兩個方法來進行大規模的像素讀寫,因爲它們的性能實在很囧;
4、託管代碼中,能不用unsafe就儘量不用。在.NET 2.0中已經提供了BitmapData類及其LockBits()、UnLockBits()操作,能夠安全地進行內存讀寫;
5、圖像的width和它存儲時的stride是不一樣的。位圖的掃描線寬度一定是4的倍數,因此圖像在內存中的大小並不是它的顯示大小;
6、Format8bppIndexed類型的PixelFormat是索引格式,其調色板並不是灰度的而是僞彩,因此需要我們對其加以修改。
代碼如下,解說寫在註釋裏了:
/// <summary>
/// 將一個字節數組轉換爲8bit灰度位圖
/// </summary>
/// <param name="rawValues">顯示字節數組</param>
/// <param name="width">圖像寬度</param>
/// <param name="height">圖像高度</param>
/// <returns>位圖</returns>
public static Bitmap ToGrayBitmap(byte[] rawValues, int width, int height)
{
//// 申請目標位圖的變量,並將其內存區域鎖定
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
//// 獲取圖像參數
int stride = bmpData.Stride; // 掃描線的寬度
int offset = stride - width; // 顯示寬度與掃描線寬度的間隙
IntPtr iptr = bmpData.Scan0; // 獲取bmpData的內存起始位置
int scanBytes = stride * height;// 用stride寬度,表示這是內存區域的大小
//// 下面把原始的顯示大小字節數組轉換爲內存中實際存放的字節數組
int posScan = 0, posReal = 0;// 分別設置兩個位置指針,指向源數組和目標數組
byte[] pixelValues = new byte[scanBytes]; //爲目標數組分配內存
for (int x = 0; x < height; x++)
{
//// 下面的循環節是模擬行掃描
for (int y = 0; y < width; y++)
{
pixelValues[posScan++] = rawValues[posReal++];
}
posScan += offset; //行掃描結束,要將目標位置指針移過那段“間隙”
}
//// 用Marshal的Copy方法,將剛纔得到的內存字節數組複製到BitmapData中
System.Runtime.InteropServices.Marshal.Copy(pixelValues, 0, iptr, scanBytes);
bmp.UnlockBits(bmpData); // 解鎖內存區域
//// 下面的代碼是爲了修改生成位圖的索引表,從僞彩修改爲灰度
ColorPalette tempPalette;
using (Bitmap tempBmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
{
tempPalette = tempBmp.Palette;
}
for (int i = 0; i < 256; i++)
{
tempPalette.Entries[i] = Color.FromArgb(i, i, i);
}
bmp.Palette = tempPalette;
//// 算法到此結束,返回結果
return bmp;
}
下面是我用來測試的代碼片段:
static void Main(string[] args)
{
byte[] bytes = new byte[10000];
int k = 0;
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
bytes[k++] = (byte)(i + j);
}
}
Bitmap bmp = ToGrayBitmap(bytes, 100, 100);
bmp.Save(@"d:\test.png",
System.Drawing.Imaging.ImageFormat.Png);
}
結果應該顯示成下面的樣子:
如果沒有修改過調色板,則會顯示出下面的色彩斑斕的圖像:
C#byte數組轉化成圖像的相關內容就向你介紹到這裏,希望對你瞭解和學習C#byte數組轉化成圖像有所幫助。
轉載自:http://developer.51cto.com/art/200908/147763.htm