实践中经常用到,故写下备用。
/// <summary>
/// 将8bit的BMP图像读入数组文件
/// </summary>
/// <param name="filePath">图像文件路径</param>
/// <returns>图像像素数组</returns>
private byte[,] ReadImage(string filePath)
{
Bitmap MyBitmap = (Bitmap)Bitmap.FromFile(filePath);
BitmapData data = MyBitmap.LockBits(new Rectangle(0, 0, MyBitmap.Width, MyBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
byte[,] pixel = new byte[data.Height, data.Width];
unsafe
{
int i, j;
byte* ptr = (byte*)(data.Scan0);
for (i = 0; i < data.Height; i++)
{
for (j = 0; j < data.Width; j++)
{
pixel[i, j] = ptr[0];
ptr++;
}
ptr += data.Stride - data.Width;
}
}
MyBitmap.UnlockBits(data);
return pixel;
}