c#调用百度AI手写文字识别
电脑版发表于:2020/2/15 15:20
封装调用接口代码:
public class BaiduAIBase64Tool { public static string Invoke(string url, string imgurl) { //string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard?access_token=" + "sdfdsf"; Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "post"; request.KeepAlive = true; // 图片的base64编码 string base64 = getFileBase64(imgurl); String str = "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(); return result; } private static String getFileBase64(String fileName) { FileStream filestream = new FileStream(fileName, FileMode.Open); byte[] arr = new byte[filestream.Length]; filestream.Read(arr, 0, (int)filestream.Length); string baser64 = Convert.ToBase64String(arr); filestream.Close(); return baser64; } }
调用:
/// <summary> /// 手写文字识别 /// </summary> /// <returns></returns> public ActionResult Handwriting() { //注意token权限问题,你可能需要在文字识别下面创建一个应用,才有对应的权限 string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting?access_token=" + AccessTokenTools.GetToken(); string result = BaiduAIBase64Tool.Invoke(host, "c:/img/a.png"); return View(); }
注意token权限问题,你可能需要在文字识别下面创建一个应用,才有对应的权限