12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- 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
- {
- /// <summary>
- /// 生成二维码
- /// </summary>
- /// <param name="context">二维码信息</param>
- 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;
- }
- /// <summary>
- /// 绘制
- /// </summary>
- /// <param name="byteMatrix">字节矩阵</param>
- /// <param name="codeColor"></param>
- /// <param name="backgroundColor"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 解析二维码
- /// </summary>
- /// <param name="bitmap">二维码</param>
- /// <returns>结果</returns>
- 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;
- }
- }
- }
|