【问题标题】:Monochrome Bitmap to Binary array in C# [duplicate]C#中的单色位图到二进制数组[重复]
【发布时间】:2012-06-12 09:01:54
【问题描述】:

可能重复:
Convert a image to a monochrome byte array

我有一个单色位图图像。我像这样加载图像:

Image image = Image.FromFile("myMonoChromeImage.bmp");

如何获得二进制数组,其中 1 代表白色像素,0 代表黑色像素,反之亦然? (数组的第一位是左上角的像素,数组的最后一位是右下角的像素)

如果可能的话,我们将不胜感激。

【问题讨论】:

  • @Panagiotis Kanavos 提到的问题是针对字节数组的。抱歉,我不知道单色位图中每个字节代表什么(8 像素?)。
  • 这是您正在寻找的问题/答案:stackoverflow.com/questions/2593768/…

标签: c# .net winforms image-processing bitmap


【解决方案1】:

您可以使用 LockBits 访问位图数据并直接从位图数组复制值。 GetPixel 基本上每次都会锁定和解锁位图,因此效率不高。

您可以将数据提取到字节数组中,然后检查 RGBA 值以查看它们是白色 (255,255,255,255) 还是黑色 (0,0,0,255)

BitmapData 类示例显示了如何执行此操作。在您的情况下,代码将是这样的:

        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);

        // Get the address of the first line.
        IntPtr ptr = bmpData.Scan0;

        // Declare an array to hold the bytes of the bitmap.
        int bytes  = Math.Abs(bmpData.Stride) * bmp.Height;
        byte[] rgbValues = new byte[bytes];

        // Copy the RGB values into the array.
        System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

        // Unlock the bits.
        bmp.UnlockBits(bmpData);

【讨论】:

  • 如何仅使用字节数组、像素格式信息、宽度和高度将其转换回位图?
  • 如果你想问一个新问题,你应该这样做。几乎没有人注意到老问题。也不可能在评论中给出正确的答案、发布代码或示例
  • 此外,无需转换任何内容。 BitmapData 对特定位图的数据进行操作。解锁后,就可以使用位图了。这也显示在链接的示例中。我怀疑你想问一个完全不同的问题,即如何从原始字节创建位图?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
  • 2018-06-27
  • 2014-03-04
相关资源
最近更新 更多