正如主题所说,我有一张.bmp
图像,我需要编写一个能够获取图像任何像素颜色的代码。这是一个 1bpp(索引)图像,因此颜色将是黑色或白色。这是我目前拥有的代码:
//This method locks the bits of line of pixels
private BitmapData LockLine(Bitmap bmp, int y)
{
Rectangle lineRect = new Rectangle(0, y, bmp.Width, 1);
BitmapData line = bmp.LockBits(lineRect,
ImageLockMode.ReadWrite,
bmp.PixelFormat);
return line;
}
//This method takes the BitmapData of a line of pixels
//and returns the color of one which has the needed x coordinate
private Color GetPixelColor(BitmapData data, int x)
{
//I am not sure if this line is correct
IntPtr pPixel = data.Scan0 + x;
//The following code works for the 24bpp image:
byte[] rgbValues = new byte[3];
System.Runtime.InteropServices.Marshal.Copy(pPixel, rgbValues, 0, 3);
return Color.FromArgb(rgbValues[2], rgbValues[1], rgbValues[0]);
}
但是我怎样才能使它适用于 1bpp 图像呢?如果我只从指针中读取一个字节,它总是有255
值,所以我假设,我做错了什么。
请不要建议使用该System.Drawing.Bitmap.GetPixel
方法,因为它运行速度太慢,我希望代码尽可能快地运行。提前致谢。
编辑: 这是可以正常工作的代码,以防万一有人需要:
private Color GetPixelColor(BitmapData data, int x)
{
int byteIndex = x / 8;
int bitIndex = x % 8;
IntPtr pFirstPixel = data.Scan0+byteIndex;
byte[] color = new byte[1];
System.Runtime.InteropServices.Marshal.Copy(pFirstPixel, color, 0, 1);
BitArray bits = new BitArray(color);
return bits.Get(bitIndex) ? Color.Black : Color.White;
}