public override async Task <string> OCRProcessAsync(Bitmap img) { if (img == null || langCode == null || langCode == "") { errorInfo = "Param Missing"; return(null); } string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + accessToken; HttpWebRequest request = WebRequest.CreateHttp(host); request.Method = "post"; request.Timeout = 8000; // 图片的base64编码 string base64 = ImageProcFunc.GetFileBase64(img); String str = "language_type=" + langCode + "&image=" + HttpUtility.UrlEncode(base64); byte[] buffer = Encoding.Default.GetBytes(str); request.ContentLength = buffer.Length; using (var requestStream = request.GetRequestStream()) { await requestStream.WriteAsync(buffer, 0, buffer.Length); } string result; try { HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); StreamReader reader = new StreamReader(response.GetResponseStream()); result = await reader.ReadToEndAsync(); response.Close(); } catch (WebException ex) { errorInfo = ex.Message; return(null); } StringBuilder sb = new StringBuilder(); BaiduOCRresOutInfo oinfo = JsonConvert.DeserializeObject <BaiduOCRresOutInfo>(result); if (oinfo.words_result != null) { for (int i = 0; i < oinfo.words_result_num; i++) { sb.AppendLine(oinfo.words_result[i].words); } return(sb.ToString()); } else { errorInfo = "UnknownError"; return(null); } }
public string OCRProcess(Bitmap img) { if (img == null || langCode == null || langCode == "") { errorInfo = "Param Missing"; return(null); } Bitmap processedImg = ImageProcFunc.Auto_Thresholding(img, imgFunc, imgFuncP1, imgFuncP2); string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + accessToken; Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host); request.Method = "post"; request.KeepAlive = true; // 图片的base64编码 string base64 = ImageProcFunc.GetFileBase64(processedImg); String str = "language_type=" + langCode + "&image=" + HttpUtility.UrlEncode(base64); byte[] buffer = encoding.GetBytes(str); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string result = reader.ReadToEnd(); string ret = ""; BaiduOCRresOutInfo oinfo = JsonConvert.DeserializeObject <BaiduOCRresOutInfo>(result); if (oinfo.words_result != null) { for (int i = 0; i < oinfo.words_result_num; i++) { ret = ret + oinfo.words_result[i].words + "\n"; } return(ret); } else { errorInfo = "UnknownError"; return(null); } }