TencentOCRTools.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using TencentCloud.Common;
  2. using TencentCloud.Ocr.V20181119.Models;
  3. using TencentCloud.Ocr.V20181119;
  4. using OASystem.Domain;
  5. using OASystem.TencentOCR;
  6. using OASystem.Domain.Dtos.Tencent;
  7. using System.Drawing;
  8. namespace OASystem.Tencent
  9. {
  10. /// <summary>
  11. /// 腾讯OCR Tools
  12. /// </summary>
  13. public class TencentOCRTool
  14. {
  15. /// <summary>
  16. /// 初始化 腾讯云账户密钥对 SecretId,SecretKey
  17. /// </summary>
  18. Credential cred = new Credential
  19. {
  20. SecretId = "AKIDoQUHLBELagatzoScfdMpMddMnz8apqIc",
  21. SecretKey = "hKiGbhkX5NWWXu3zDWwAATVK3e5sWuBB"
  22. };
  23. /// <summary>
  24. /// ocr识别
  25. /// </summary>
  26. /// <param name="picBase64">图片base64</param>
  27. /// <param name="ocrEnum">转换类型</param>
  28. /// <param name="data">请求数据源</param>
  29. /// <returns></returns>
  30. public Result GetOCR(TencentOCREnum ocrEnum, object data)
  31. {
  32. Result result = new Result { Code = -1, Msg = "未知错误", Data = null };
  33. OcrClient client = new OcrClient(cred, "ap-guangzhou");
  34. try
  35. {
  36. switch (ocrEnum)
  37. {
  38. case 0: //身份证识别
  39. IDCardOCRDto iDCardDto = (IDCardOCRDto)data;
  40. IDCardOCRRequest req = new IDCardOCRRequest();
  41. if (iDCardDto.CardSide == 0) req.CardSide = "FORNT";
  42. else if (iDCardDto.CardSide == 0) req.CardSide = "BACK";
  43. req.ImageBase64 = iDCardDto.picBase64;
  44. IDCardOCRResponse resp = client.IDCardOCRSync(req);
  45. result.Data = resp;
  46. break;
  47. }
  48. result.Code = 0;
  49. result.Msg = "成功";
  50. return result;
  51. }
  52. catch (Exception ex)
  53. {
  54. result.Msg = "类型:" + ex.Message;
  55. return result;
  56. }
  57. }
  58. /// <summary>
  59. /// 图片转Base64
  60. /// </summary>
  61. /// <param name="ImageFileName">图片的完整路径</param>
  62. /// <returns></returns>
  63. public string ImgToBase64(string ImageFileName)
  64. {
  65. try
  66. {
  67. Bitmap bmp = new Bitmap(ImageFileName);
  68. MemoryStream ms = new MemoryStream();
  69. bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  70. byte[] arr = new byte[ms.Length];
  71. ms.Position = 0;
  72. ms.Read(arr, 0, (int)ms.Length);
  73. ms.Close();
  74. return Convert.ToBase64String(arr);
  75. }
  76. catch (Exception e)
  77. {
  78. return e.Message.ToString();
  79. }
  80. }
  81. }
  82. }