using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using com.google.zxing; using System.Drawing; namespace tool { public static class QRcodeGenerator { /// /// 生成二维码 /// /// 二维码信息 public static Bitmap Encode(string context) { Bitmap bitmap = null; try { int codeSize = 200; string codeColor = "0x" + "000000"; string backgroundColor = "0x" + "FFFFFF"; //字节矩阵(google,用于生成QR_CODE) com.google.zxing.common.ByteMatrix byteMatrix = new MultiFormatWriter().encode(context, BarcodeFormat.QR_CODE, codeSize, codeSize); //将字节矩阵转换成二维码(google) bitmap = ToBitmap(byteMatrix, codeColor, backgroundColor); } catch (Exception ex) { Log.Instance.WriteLog(LogType.PROCESS, LogFile.LOG, "二维码信息:"+ex.Message); } return bitmap; } /// /// 绘制 /// /// 字节矩阵 /// /// /// private static Bitmap ToBitmap(com.google.zxing.common.ByteMatrix byteMatrix, string codeColor, string backgroundColor) { int width = byteMatrix.Width; int height = byteMatrix.Height; //设置二维码的长、宽和各个像素点的颜色 Bitmap bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //遍历各个像素点 for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { bitmap.SetPixel(x, y, byteMatrix.get_Renamed(x, y) != -1 ? ColorTranslator.FromHtml(codeColor) : ColorTranslator.FromHtml(backgroundColor)); } } return bitmap; } /// /// 解析二维码 /// /// 二维码 /// 结果 public static Result DeCode(Bitmap bitmap) { LuminanceSource source = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height); com.google.zxing.BinaryBitmap binaryBitmap = new com.google.zxing.BinaryBitmap(new com.google.zxing.common.HybridBinarizer(source)); Result result = null; try { result = new MultiFormatReader().decode(binaryBitmap); } catch (Exception ex) { Console.WriteLine("解析错误" + ex.Message); } return result; } } }