QRcodeGenerator.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using com.google.zxing;
  7. using System.Drawing;
  8. namespace tool
  9. {
  10. public static class QRcodeGenerator
  11. {
  12. /// <summary>
  13. /// 生成二维码
  14. /// </summary>
  15. /// <param name="context">二维码信息</param>
  16. public static Bitmap Encode(string context)
  17. {
  18. Bitmap bitmap = null;
  19. try
  20. {
  21. int codeSize = 200;
  22. string codeColor = "0x" + "000000";
  23. string backgroundColor = "0x" + "FFFFFF";
  24. //字节矩阵(google,用于生成QR_CODE)
  25. com.google.zxing.common.ByteMatrix byteMatrix = new MultiFormatWriter().encode(context, BarcodeFormat.QR_CODE, codeSize, codeSize);
  26. //将字节矩阵转换成二维码(google)
  27. bitmap = ToBitmap(byteMatrix, codeColor, backgroundColor);
  28. }
  29. catch (Exception ex)
  30. {
  31. Log.Instance.WriteLog(LogType.PROCESS, LogFile.LOG, "二维码信息:"+ex.Message);
  32. }
  33. return bitmap;
  34. }
  35. /// <summary>
  36. /// 绘制
  37. /// </summary>
  38. /// <param name="byteMatrix">字节矩阵</param>
  39. /// <param name="codeColor"></param>
  40. /// <param name="backgroundColor"></param>
  41. /// <returns></returns>
  42. private static Bitmap ToBitmap(com.google.zxing.common.ByteMatrix byteMatrix, string codeColor, string backgroundColor)
  43. {
  44. int width = byteMatrix.Width;
  45. int height = byteMatrix.Height;
  46. //设置二维码的长、宽和各个像素点的颜色
  47. Bitmap bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  48. //遍历各个像素点
  49. for (int x = 0; x < width; x++)
  50. {
  51. for (int y = 0; y < height; y++)
  52. {
  53. bitmap.SetPixel(x, y, byteMatrix.get_Renamed(x, y) != -1 ? ColorTranslator.FromHtml(codeColor) : ColorTranslator.FromHtml(backgroundColor));
  54. }
  55. }
  56. return bitmap;
  57. }
  58. /// <summary>
  59. /// 解析二维码
  60. /// </summary>
  61. /// <param name="bitmap">二维码</param>
  62. /// <returns>结果</returns>
  63. public static Result DeCode(Bitmap bitmap)
  64. {
  65. LuminanceSource source = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
  66. com.google.zxing.BinaryBitmap binaryBitmap = new com.google.zxing.BinaryBitmap(new com.google.zxing.common.HybridBinarizer(source));
  67. Result result = null;
  68. try
  69. {
  70. result = new MultiFormatReader().decode(binaryBitmap);
  71. }
  72. catch (Exception ex)
  73. {
  74. Console.WriteLine("解析错误" + ex.Message);
  75. }
  76. return result;
  77. }
  78. }
  79. }