读取单色位图像素颜色

Tim*_*hyP 3 .net c# graphics drawing bitmap

我不知道一个更好的头衔,但我会描述这个问题.

我们使用的硬件具有显示图像的能力.它可以显示分辨率为64 x 256的黑白图像.

问题是我们必须发送到设备的图像格式.它不是标准的位图格式,而是一个代表图像每个像素的字节数组.

0 =黑色,1 =白色.

因此,如果我们有一个大小为4 x 4的图像,则字节数组可能如下所示:

1000 0100 0010 0001

图像看起来像:

位图http://www.mediafire.com/imgbnc.php/6ee6a28148d0170708cb10ec7ce6512e4g.jpg

问题是我们需要通过在C#中创建单色位图来创建此图像,然后将其转换为设备可以理解的文件格式.

例如,可以在设备上显示文本.为此,他必须创建一个位图并向其写入文本:

var bitmap = new Bitmap(256, 64);

using (var graphics = Graphics.FromImage(bitmap))
{
    graphics.DrawString("Hello World", new Font("Courier", 10, FontStyle.Regular), new SolidBrush(Color.White), 1, 1);
}
Run Code Online (Sandbox Code Playgroud)

这里有两个问题:

  1. 生成的位图不是单色的
  2. 生成的位图具有不同的二进制格式

所以我需要一种方法:

  1. 在.NET中生成单色位图
  2. 读取位图中每个像素的各个像素颜色

我发现你可以将像素深度设置为16,24或32位,但没有找到单色,我不知道如何读取像素数据.

欢迎提出建议.

更新:我不能使用Win32 PInvokes ...必须是平台中立的!

关注:以下代码现在适用于我.(以防任何人需要)

private static byte[] GetLedBytes(Bitmap bitmap)
{
    int threshold = 127;
    int index = 0;
    int dimensions = bitmap.Height * bitmap.Width;

    BitArray bits = new BitArray(dimensions);

    //Vertically
    for (int y = 0; y < bitmap.Height; y++)
    {
        //Horizontally
        for (int x = 0; x < bitmap.Width; x++)
        {
            Color c = bitmap.GetPixel(x, y);
            int luminance = (int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11);
            bits[index] = (luminance > threshold);
            index++;
        }
    }

    byte[] data = new byte[dimensions / 8];
    bits.CopyTo(data, 0);
    return data;
}
Run Code Online (Sandbox Code Playgroud)

aru*_*rul 6

我计算每个像素的亮度,然后将其与某个阈值进行比较.

y=0.3*R+0.59G*G+0.11*B
Run Code Online (Sandbox Code Playgroud)

假设阈值为127:

const int threshold = 127;
Bitmap bm = { some source bitmap };

byte[,] buffer = new byte[64,256];

for(int y=0;y<bm.Height;y++)
{
  for(int x=0;x<bm.Width;x++)
  {
   Color c=source.GetPixel(x,y);
   int luminance = (int)(c.R*0.3 + c.G*0.59+ c.B*0.11);
   buffer[x,y] = (luminance  > 127) ? 1 : 0;
  }
}
Run Code Online (Sandbox Code Playgroud)