最近遇到使用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時就是需要每個像素重繪一遍。這樣生成的圖形就是黑白兩種顏色的。