1. 程式人生 > >C#生成二維碼,裁切邊框

C#生成二維碼,裁切邊框

google tasks html fff white zxing ace sta wim

使用google zxing生成的二維碼帶有白色邊框,顯示在報告(使用Crystal Report 水晶報表)上時,由於空間有限造成二維碼過小難以掃描識別。

通過將白色邊框裁切掉,可以在有限的空間內最大化顯示二維碼。

using com.google.zxing;
using com.google.zxing.common;
using com.google.zxing.qrcode.decoder;
using java.awt.image;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sunway.Barcode { /// <summary> /// /// </summary> public static class BarcodeHelper { /// <summary> /// /// </summary>
/// <param name="info"></param> /// <returns></returns> public static string CreateBarcode(string info) { string filePath = string.Empty; filePath = Guid.NewGuid().ToString() + ".png"; // try { MultiFormatWriter writer
= new MultiFormatWriter(); Hashtable hints = new Hashtable(); hints.Add(EncodeHintType.CHARACTER_SET, "utf-8"); //編碼 ErrorCorrectionLevel level = ErrorCorrectionLevel.H; hints.Add(EncodeHintType.ERROR_CORRECTION, level); //容錯率 //hints.Add(EncodeHintType.MARGIN, 0); //二維碼邊框寬度,這裏文檔說設置0-4, ByteMatrix byteMatrix = writer.encode(info, BarcodeFormat.QR_CODE, 300, 300, hints); Bitmap bitmap = ToBitmap(byteMatrix); // bitmap.Save(filePath); } catch (Exception) { filePath = string.Empty; throw; } finally { } // return filePath; } /// <summary> /// 轉換為位圖 /// </summary> /// <param name="matrix"></param> /// <returns></returns> public static Bitmap ToBitmap(ByteMatrix matrix) { int width = matrix.Width; int height = matrix.Height; //32位ARGB格式 Bitmap bmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Color colorBlack = ColorTranslator.FromHtml("0xFF000000");//黑色 Color colorWhite = ColorTranslator.FromHtml("0xFFFFFFFF");//白色 // 二維矩陣轉為一維像素數組,也就是一直橫著排了 //Color[] pixels = new int[width * height]; bool isFirstBlackPoint = false; int startX = 0; int startY = 0; //循環內容矩陣,寫入白、黑點 for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (matrix.get_Renamed(x, y) != -1)//返回白點/黑點 { if (!isFirstBlackPoint) { isFirstBlackPoint = true; startX = x;//二維碼自帶一個白色邊框,邊框內左上角是黑點,記錄左上角的坐標點 startY = y; } } bmap.SetPixel(x, y, matrix.get_Renamed(x, y) != -1 ? colorBlack : colorWhite); } } #region 判斷並截取 int PADDING_SIZE_MIN = 2; int x1 = startX - PADDING_SIZE_MIN; int y1 = startY - PADDING_SIZE_MIN; if (x1 < 0 || y1 < 0) { return bmap; } else { int w1 = width - x1 * 2; int h1 = height - y1 * 2; Bitmap bitmapQR = CutImage(bmap, new Rectangle(x1, y1, w1, h1)); return bitmapQR; } #endregion } /// <summary> /// 截取圖片,指定截取區域(開始位置和長度/寬度) /// </summary> /// <param name="img"></param> /// <param name="rect"></param> /// <returns></returns> private static Bitmap CutImage(Image img, Rectangle rect) { Bitmap b = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(b); g.DrawImage(img, 0, 0, rect, GraphicsUnit.Pixel); g.Dispose(); return b; } } }

C#生成二維碼,裁切邊框