C#打印像素值

kli*_*ijo 3 c# image

我有一个8位的位图彩色图像。当我做一个

Color pixelcolor = b.GetPixel(j,i);    
Console.Write(pixelcolor.ToString() + " " );
Run Code Online (Sandbox Code Playgroud)

我懂了

 Color [A=255, R=255, G=255, B=255]
Run Code Online (Sandbox Code Playgroud)

我只需要获取8位值。不是R,G,B和A的24位单独值。

vid*_*ige 5

无法Bitmap直接使用该类来执行此操作。但是,您可以使用该LockBits方法直接访问像素。

使用不安全代码:(请记住要先在项目中启用不安全代码

public static unsafe Byte GetIndexedPixel(Bitmap b, Int32 x, Int32 y)
{
    if (b.PixelFormat != PixelFormat.Format8bppIndexed) throw new ArgumentException("Image is not in 8 bit per pixel indexed format!");
    if (x < 0 || x >= b.Width) throw new ArgumentOutOfRangeException("x", string.Format("x should be in 0-{0}", b.Width));
    if (y < 0 || y >= b.Height) throw new ArgumentOutOfRangeException("y", string.Format("y should be in 0-{0}", b.Height));
    BitmapData data = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, b.PixelFormat);
    try
    {
        Byte* scan0 = (Byte*)data.Scan0;
        return scan0[x + y * data.Stride];
    }
    finally
    {
        if (data != null) b.UnlockBits(data);
    }
}
Run Code Online (Sandbox Code Playgroud)

安全的替代方法,使用Marshal.Copy

public static Byte GetIndexedPixel(Bitmap b, Int32 x, Int32 y)
{
    if (b.PixelFormat != PixelFormat.Format8bppIndexed) throw new ArgumentException("Image is not in 8 bit per pixel indexed format!");
    if (x < 0 || x >= b.Width) throw new ArgumentOutOfRangeException("x", string.Format("x should be in 0-{0}", b.Width));
    if (y < 0 || y >= b.Height) throw new ArgumentOutOfRangeException("y", string.Format("y should be in 0-{0}", b.Height));
    BitmapData data = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, b.PixelFormat);
    try
    {
        Byte[] pixel = new Byte[1];
        Marshal.Copy(new IntPtr(data.Scan0.ToInt64() + x + y * data.Stride), pixel, 0, 1);
        return pixel[0];
    }
    finally
    {
        if (data != null) b.UnlockBits(data);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的...直接使用此代码会遇到与普通GetPixel相同的问题:在遍历所有内容时,必须对可能具有数千甚至上万个图像的图像上的每个像素进行锁定和解锁众所周知,它的速度很慢,而仅检查字节数组的内容很快。 (2认同)