C# C语言中从单色位图到二进制数组的转换#
可能重复:C# C语言中从单色位图到二进制数组的转换#,c#,.net,winforms,image-processing,bitmap,C#,.net,Winforms,Image Processing,Bitmap,可能重复: 我有一个单色位图图像。我像这样加载图像: Image image = Image.FromFile("myMonoChromeImage.bmp"); Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);
我有一个单色位图图像。我像这样加载图像:
Image image = Image.FromFile("myMonoChromeImage.bmp");
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);
如何获得二进制数组,其中1表示白色像素,0表示黑色像素,反之亦然?(阵列中的第一位是左上角像素,阵列中的最后一位是右下角像素)
如果可能的话,一种有效的方法是值得赞赏的。您可以使用锁位来访问位图数据,并直接从位图数组复制值。GetPixel基本上每次都会锁定和解锁位图,因此效率不高 您可以将数据提取到字节数组,然后检查RGBA值,查看它们是白色(255255)还是黑色(0,0,0255) 类示例演示了如何执行此操作。在您的情况下,代码如下所示:
Image image = Image.FromFile("myMonoChromeImage.bmp");
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);
@Panagiotis Kanavos提到的问题是字节数组。很抱歉,我不知道在单色位图(8像素?)中每个字节代表什么。这是您正在寻找的问题/答案:。如何使用字节数组、像素格式信息、宽度和高度将其转换回位图?如果您想问新问题,您应该这样做。几乎没有人注意到对老问题的评论。在评论中也不可能给出正确的答案、张贴代码或示例。此外,不需要转换任何内容。BitmapData对特定位图的数据进行操作。解锁后,可以使用位图。链接示例中也显示了这一点。我怀疑你想问一个完全不同的问题,即如何从原始字节创建位图?