如何用C#从二维码BMP图片提取黑白像素二维数组?
需求:将BMP格式二维码图片转换为黑白像素二维数组
需要编写C#程序读取BMP二维码图片,将其转换为1表示黑色像素、0表示白色像素的二维数组,期望输出格式如下:
{ {1,1,1,1,1,1,1,0,0,0,1,0,1,0,1,1,1,1,1,1,1}, {1,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1}, {1,0,1,1,1,0,1,0,1,0,1,1,0,0,1,0,1,1,1,0,1}, {1,0,1,1,1,0,1,0,0,0,0,0,1,0,1,0,1,1,1,0,1}, {1,0,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,0,1}, {1,0,0,0,0,0,1,0,1,1,1,0,0,0,1,0,0,0,0,0,1}, {1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1}, {0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,1,0,0,1,1,0,0,1,1,1,0,1,1,1,0,1,1,0}, {1,1,1,1,1,1,0,0,1,0,0,1,0,1,0,1,0,1,1,1,1}, {0,1,1,0,0,0,1,1,0,1,1,1,0,0,1,1,1,1,1,0,1}, {1,0,0,1,1,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1}, {0,1,1,0,1,1,1,1,0,0,1,1,0,1,1,1,0,0,1,0,0}, {0,0,0,0,0,0,0,0,1,1,0,0,0,1,1,0,1,0,1,0,0}, {1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,0,1,1,0,1,0}, {1,0,0,0,0,0,1,0,0,1,1,0,0,0,1,0,0,0,1,1,1}, {1,0,1,1,1,0,1,0,0,0,0,0,1,1,1,0,0,0,1,1,1}, {1,0,1,1,1,0,1,0,1,0,0,0,0,1,1,1,0,0,0,1,1}, {1,0,1,1,1,0,1,0,0,1,1,1,0,1,1,1,0,1,1,0,1}, {1,0,0,0,0,0,1,0,1,0,1,1,1,0,0,1,0,1,0,0,0}, {1,1,1,1,1,1,1,0,1,0,1,0,0,1,0,1,0,0,1,1,0} }
现有代码(仅实现文本解码)
目前已使用ZXing库的MultiFormatReader实现二维码文本解码,但无法获取目标二维数组,代码片段如下:
Bitmap originalBitmap = new Bitmap(pathOfBmp); LuminanceSource source; source = new BitmapLuminanceSource(originalBitmap); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result = new MultiFormatReader().decode(bitmap); Console.WriteLine(result.Text);
解决方案:获取二值化像素矩阵并转换为目标格式
你可以直接通过ZXing的BinaryBitmap对象获取二值化后的像素数据,无需额外处理原始Bitmap。以下是完整实现代码:
using System; using System.Drawing; using ZXing; using ZXing.Common; class Program { static void Main(string[] args) { string pathOfBmp = "your_qr_code.bmp"; Bitmap originalBitmap = new Bitmap(pathOfBmp); // 生成二值化Bitmap(复用你已有的代码) LuminanceSource source = new BitmapLuminanceSource(originalBitmap); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source)); // 获取二维码的宽高 int width = binaryBitmap.Width; int height = binaryBitmap.Height; // 初始化二维数组 int[,] pixelArray = new int[height, width]; // 遍历每个像素,转换为1(黑)或0(白) for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // ZXing中getPixel返回true表示黑色像素 pixelArray[y, x] = binaryBitmap.GetPixel(x, y) ? 1 : 0; } } // 按照期望格式输出二维数组 Console.WriteLine("{"); for (int y = 0; y < height; y++) { Console.Write(" {"); for (int x = 0; x < width; x++) { Console.Write(pixelArray[y, x]); if (x != width - 1) { Console.Write(","); } } Console.Write("}"); if (y != height - 1) { Console.Write(","); } Console.WriteLine(); } Console.WriteLine("}"); } }
关键说明
binaryBitmap.GetPixel(x, y):返回true代表当前坐标为黑色像素,直接转换为1;false代表白色像素,转换为0。- 坐标遍历顺序:
y从0到height-1对应图片的从上到下,x从0到width-1对应图片的从左到右,与常规图片像素坐标一致。 - 输出格式严格匹配你给出的示例,每行数组前添加4个空格,元素用逗号分隔,最后闭合大括号。
内容的提问来源于stack exchange,提问作者AgileFever
相关产品推荐
相关产品推荐

