用指针读BMP图像

实践中经常用到,故写下备用。

/// <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;
}

posted on 2012-10-15 20:23  guyichang  阅读(342)  评论(0编辑  收藏  举报

导航