C# 中的单色位图到二进制数组

本文关键字:二进制 数组 位图 单色 | 更新日期: 2023-09-27 18:36:57

可能的重复项:
将图像转换为单色字节数组

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

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

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

如果可能的话,希望能采取有效的办法。

C# 中的单色位图到二进制数组

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

您可以将数据提取到字节数组,然后检查 RGBA 值以查看它们是白色

(255,255,255,255) 还是黑色 (0,0,0,255)

位图数据类示例演示如何执行此操作。在您的情况下,代码将是这样的:

        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);