You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
3.3 KiB

2 years ago
  1. using EasyBL.WebApi.Message;
  2. using System;
  3. using System.Drawing;
  4. using System.IO;
  5. using ThoughtWorks.QRCode.Codec;
  6. namespace EasyBL
  7. {
  8. public class QRCodeService : ServiceBase
  9. {
  10. /// <summary>
  11. /// 產生二維碼
  12. /// </summary>
  13. /// <param name="i_crm">todo: describe i_crm parameter on GetQRCode</param>
  14. /// <returns></returns>
  15. public ResponseMessage GetQRCode(RequestMessage i_crm)
  16. {
  17. ResponseMessage rm = null;
  18. string sMsg = null;
  19. var sPath = @"Document/EurotranFile/QRCode";
  20. try
  21. {
  22. var sKey = _fetchString(i_crm, "guid");
  23. var sSize = _fetchString(i_crm, "size") ?? "8";
  24. var iSize = int.Parse(sSize);
  25. var bs = Create_ImgCode(sKey, iSize);
  26. var sImgPath = SaveImg(ref sPath, bs);
  27. if (!File.Exists(sImgPath))
  28. {
  29. sMsg = "產生失敗";
  30. }
  31. rm = new SuccessResponseMessage(null, i_crm);
  32. rm.DATA.Add(BLWording.REL, sPath);
  33. }
  34. catch (Exception ex)
  35. {
  36. sMsg = Util.GetLastExceptionMsg(ex);
  37. }
  38. finally
  39. {
  40. if (null != sMsg)
  41. {
  42. rm = new ErrorResponseMessage(sMsg, i_crm);
  43. }
  44. }
  45. return rm;
  46. }
  47. /// <summary>
  48. /// 生成二维码图片
  49. /// </summary>
  50. /// <param name="codeNumber">要生成二维码的字符串</param>
  51. /// <param name="size">大小尺寸</param>
  52. /// <returns>二维码图片</returns>
  53. public static Bitmap Create_ImgCode(string codeNumber, int size)
  54. {
  55. //创建二维码生成类
  56. var qrCodeEncoder = new QRCodeEncoder
  57. {
  58. //设置编码模式
  59. QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE,
  60. //设置编码测量度
  61. QRCodeScale = size,
  62. //设置编码版本
  63. QRCodeVersion = 0,
  64. //设置编码错误纠正
  65. QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M
  66. };
  67. //生成二维码图片
  68. var image = qrCodeEncoder.Encode(codeNumber);
  69. return image;
  70. }
  71. /// <summary>
  72. /// 保存图片
  73. /// </summary>
  74. /// <param name="sPath">保存路径</param>
  75. /// <param name="img">图片</param>
  76. public string SaveImg(ref string sPath, Bitmap img)
  77. {
  78. var sSavePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, sPath);
  79. //保存图片到目录
  80. if (Directory.Exists(sSavePath))
  81. {
  82. //文件名称
  83. var guid = Guid.NewGuid().ToString().Replace("-", "") + ".png";
  84. img.Save(sSavePath + "/" + guid, System.Drawing.Imaging.ImageFormat.Png);
  85. sPath += "/" + guid;
  86. sSavePath += "/" + guid;
  87. }
  88. else
  89. {
  90. //当前目录不存在,则创建
  91. Directory.CreateDirectory(sSavePath);
  92. this.SaveImg(ref sPath, img);
  93. }
  94. return sSavePath;
  95. }
  96. }
  97. }