C#位图指针操作的漂亮写法


丑陋的写法:

for (int y = 0; y < data.Height; y++)
{
    for (int x = 0; x < data.Width; x++)
    {
        // write the logic implementation here

        ptr += 3;
    }
    ptr += data.Stride - data.Width * 3;
}

优雅的写法:

using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

--------------------------------------------------------

if (Path.GetExtension(file_path) != ".png")
{
    return false;
}

Bitmap bmp = new Bitmap(file_path);
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

// 开启unsafe模式 项目 → 右键 → Properties → Build → Allow unsafe code
unsafe
{
    byte* pData = (byte*)(data.Scan0);

    //int pixelBytes = 4; // 每个像素的字节数
    int pixelBytes = (data.Stride / data.Width); // 每个像素的字节数 = (每行的字节数/每行的像素数)

    //[0]B [1]G [2]R [3]A
    for (int y = 0; y < data.Height; y++)
    {
        for (int x = 0; x < data.Width; x++)
        {
            // 计算指针偏移量
            byte* pPiexl = pData + (y * data.Stride) + (x * pixelBytes);

            byte b = pPiexl[0];
            byte g = pPiexl[1];
            byte r = pPiexl[2];
            byte a = pPiexl[3];
            /*
            byte b = pData[y*data.Stride + x*pixelBytes + 0];
            byte g = pData[y*data.Stride + x*pixelBytes + 1];
            byte r = pData[y*data.Stride + x*pixelBytes + 2];
            byte a = pData[y*data.Stride + x*pixelBytes + 3];
            */

            Console.Write("[" + String.Format("{0,3:000}", a) + "," + String.Format("{0,3:000}", r) + "," + String.Format("{0,3:000}", g) + "," + String.Format("{0,3:000}", b) + "]");
        }
        Console.WriteLine("\r\n");
    }

}

bmp.UnlockBits(data);
bmp.Dispose();

你可能感兴趣的:(image,C#,unsafe)