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, );
//设置纠错级别
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 = ; x < byteMatrix.Width; x++)
{
for (int y = ; y < byteMatrix.Width; y++)
{
if (byteMatrix[y, x])
{
if (graphics != null)
graphics.FillRectangle(Brushes.Black, x + viewX, y + viewY, , );
imgInfo.SetPixel(x, y, Color.Black);
}
else
{
if (graphics != null)
graphics.FillRectangle(Brushes.White, x + viewX, y + viewY, , );
imgInfo.SetPixel(x, y, Color.White);
}
}
}

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

上一篇:Python可视化学习(2):Matplotlib快速绘图基础


下一篇:tomcat开启远程调试和热部署(jrebel)启动tomcat