C# GDI+绘制一维条码打印模糊的解决办法

最近遇到使用zxing生成的一维条码打印出来的条码图形很模糊根本识别不了。其实原因只有一句话: bitmap没有直接使用PrintDocument的Graphics画布进行绘制,而是中间处理了一下外部传过来一个图片,这个图片看起来很成像质量很好,但其实是一个彩色图片,一维条码是由黑白两种颜色组成的,没有灰度是两种纯色。这样打印出来的图片看起来有毛刺,直线不连续了。解决方法是减少中间环节直接把zxing生成的bitmap对象使用"PrintDocument的Graphics画布"绘制。PrintDocument的Graphics和Bitmap的Graphics要是同一个对象。

 

记录一下,zxing生成黑白图片的办法:

复制代码
Dictionary<EncodeHintType, Object> hintMap = new Dictionary<EncodeHintType, Object>();
                   //设置编码
                   hintMap.Add(EncodeHintType.CHARACTER_SET, "UTF-8");

                   // Now with zxing version 3.2.1 you could change border size (white
                   // border size to just 1)
                   //设置间距
                   hintMap.Add(EncodeHintType.MARGIN, 0);
                   //设置纠错级别
                   hintMap.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

                   QRCodeWriter qrCodeWriter = new QRCodeWriter();
                   //ZXing.MultiFormatWriter qrCodeWriter = new ZXing.MultiFormatWriter();//new QRCodeWriter();
                   //BitMatrix 根据其需要输出的参数,和设置条件等新建BitMatrix对象
                   BitMatrix byteMatrix = qrCodeWriter.encode(value, BarcodeFormat.QR_CODE, width, height, hintMap);

                   var imgInfo = new Bitmap(width, height);

                   for (int x = 0; x < byteMatrix.Width; x++)
                   {
                       for (int y = 0; y < byteMatrix.Width; y++)
                       {
                           if (byteMatrix[y, x])
                           {
                               if (graphics != null)
                                   graphics.FillRectangle(Brushes.Black, x + viewX, y + viewY, 1, 1);
                               imgInfo.SetPixel(x, y, Color.Black);
                           }
                           else
                           {
                               if (graphics != null)
                                   graphics.FillRectangle(Brushes.White, x + viewX, y + viewY, 1, 1);
                               imgInfo.SetPixel(x, y, Color.White);
                           }
                       }
                   }
复制代码

BitMatrix是zxing将字符Encode成条码图形的一种返回值类型,是条码图形的矩阵表示方式。转换成bitmap时就是需要每个像素重绘一遍。这样生成的图形就是黑白两种颜色的。

posted @   数据酷软件  阅读(2161)  评论(1编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示