RecogApi.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Net.Http.Headers;
  10. using MeterVision.Config;
  11. using System.Drawing;
  12. namespace MeterVision.RemoteApi
  13. {
  14. //识别时传入的数据(目前无用)
  15. public class MetaData
  16. {
  17. public int Width { get; set; }
  18. public int Height { get; set; }
  19. public int Size { get; set; }
  20. public MetaData()
  21. {
  22. Width = 320;
  23. Height = 240;
  24. Size = 0;
  25. }
  26. }
  27. public class ApiResponse
  28. {
  29. public int StatusCode { get; set; }
  30. public string ResponseBody { get; set; }
  31. public bool IsSuccess => StatusCode >= 200 && StatusCode < 300;
  32. }
  33. //返回的Response中的对象
  34. public class RecognResult<T>
  35. {
  36. public int result { get; set; } // 1=成功, 0=失败
  37. public T data { get; set; } // 泛型数据部分
  38. public string message { get; set; } // 提示信息
  39. }
  40. //ApiResponse中的数据对象
  41. public class RecognData
  42. {
  43. //没有识别出水表类别:0
  44. //数字+指针水表:1
  45. //全数字水表:2
  46. //全指针水表:3
  47. //压力表类型: 5
  48. //水表没有摆正的图片:88
  49. //只要有一个数字的概率低于50%:90
  50. public int? meter_type { get; set; } //水表类型
  51. public string image { get; set; } // base64 编码图像
  52. public string logs { get; set; } // base64 编码日志
  53. public double? reading { get; set; } // 数值
  54. // 可扩展字段,如:
  55. // public string timestamp { get; set; }
  56. public double? reading_unit { get; set; } //读数单位
  57. }
  58. //调用结果对象
  59. public class CallApiResult
  60. {
  61. public int callResult { get; set; } //1:调用成功,0:调用时出错
  62. public string errorMessage { get; set; } //调用出错时的错误消息
  63. //调用成功时的返回对象
  64. public RecognResult<RecognData> recognResult { get; set; }
  65. }
  66. //识别接口
  67. public class RecogApi
  68. {
  69. //设置超时时间5秒
  70. private static readonly HttpClient _client = new HttpClient
  71. {
  72. Timeout = TimeSpan.FromSeconds(5)
  73. };
  74. //调用识别
  75. public static async Task<CallApiResult> CallRecogn(string imagePath,MetaData metadata)
  76. {
  77. //判断凸显尺寸是否合规
  78. if (!ThisApp.IsImageDimensionsValid(imagePath))
  79. {
  80. return new CallApiResult
  81. {
  82. callResult = 0,
  83. errorMessage = $"{imagePath}图像尺寸不合规",
  84. recognResult = null
  85. };
  86. }
  87. try
  88. {
  89. string _url = CfginiItem.GetConfigItem().HttpApi;
  90. var metadataJson = JsonConvert.SerializeObject(metadata);
  91. using (var form = new MultipartFormDataContent())
  92. using (var fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read, FileShare.Read))
  93. using (var imageContent = new StreamContent(fs))
  94. {
  95. imageContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
  96. form.Add(imageContent, "image", Path.GetFileName(imagePath));
  97. var metadataContent = new StringContent(metadataJson, Encoding.UTF8, "application/json");
  98. form.Add(metadataContent, "metadata");
  99. //HttpResponseMessage response = _client.PostAsync(_url, form).GetAwaiter().GetResult();
  100. HttpResponseMessage response = await _client.PostAsync(_url, form);
  101. if (!response.IsSuccessStatusCode)
  102. {
  103. return new CallApiResult
  104. {
  105. callResult = 0,
  106. errorMessage = $"接口返回错误:{(int)response.StatusCode} - {response.ReasonPhrase}",
  107. recognResult = null
  108. };
  109. }
  110. string responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
  111. //解析JSON响应体
  112. var result = JsonConvert.DeserializeObject<RecognResult<RecognData>>(responseBody);
  113. return new CallApiResult
  114. {
  115. callResult = 1,
  116. errorMessage = null,
  117. recognResult = result
  118. };
  119. }
  120. }
  121. catch(JsonException ex)
  122. {
  123. return new CallApiResult
  124. {
  125. callResult = 0,
  126. errorMessage = $"JSON解析失败: {ex.Message}",
  127. recognResult = null
  128. };
  129. }
  130. catch(HttpRequestException ex)
  131. {
  132. return new CallApiResult
  133. {
  134. callResult = 0,
  135. errorMessage = $"网络异常: {ex.Message}",
  136. recognResult = null
  137. };
  138. }
  139. catch(IOException ex)
  140. {
  141. return new CallApiResult
  142. {
  143. callResult = 0,
  144. errorMessage = $"读取文件错误: {ex.Message}",
  145. recognResult = null
  146. };
  147. }
  148. catch(Exception ex)
  149. {
  150. return new CallApiResult
  151. {
  152. callResult = 0,
  153. errorMessage = $"调用失败: {ex.Message}",
  154. recognResult = null
  155. };
  156. }
  157. }
  158. //报错图像数据
  159. public static bool SaveBase64ToFile(string base64Data, string filePath)
  160. {
  161. if (string.IsNullOrWhiteSpace(base64Data)) return false;
  162. try
  163. {
  164. // 处理可能带有 data URI 前缀的 base64 字符串
  165. var commaIndex = base64Data.IndexOf(',');
  166. if (commaIndex >= 0)
  167. {
  168. base64Data = base64Data.Substring(commaIndex + 1);
  169. }
  170. byte[] fileBytes = Convert.FromBase64String(base64Data);
  171. File.WriteAllBytes(filePath, fileBytes);
  172. return true;
  173. }
  174. catch (FormatException)
  175. {
  176. return false;
  177. //MessageBox.Show("Base64 解码失败,数据格式错误。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  178. }
  179. catch (IOException ex)
  180. {
  181. //MessageBox.Show($"写入文件失败: {ex.Message}", "IO 错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  182. Console.WriteLine(ex.Message);
  183. return false;
  184. }
  185. }
  186. //---------------------------------------------------------------------
  187. }
  188. }