OCR智能識別身份信息

本人研究了兩款OCR智能識別的API,下面作詳解!json

第一款是百度雲的OCR識別,填寫配置信息,天天有五百次免費的識別次數,適合中小型客戶流量能夠使用。API文檔:http://ai.baidu.com/docs#/OCR-API/topapi

     public static String Token = ""; // 調用getAccessToken()獲取的 access_token建議根據expires_in 時間 設置緩存
        private static String clientId = SysConfigManager.Get("bdy_config", "api_key");//"**********"; // 百度雲中開通對應服務應用的 API Key 建議開通應用的時候多選服務
        private static String clientSecret = SysConfigManager.Get("bdy_config", "Secret_Key");//"***********"; 

     /// <summary>
        /// 獲取百度雲 access_token
        /// </summary>
        /// <returns></returns>
        public static string GetbaiduAccessToken()
        {
            Token = Convert.ToString(HiCache.Get("access_token"));
            if (string.IsNullOrEmpty(Token))
            {
                String authHost = "https://aip.baidubce.com/oauth/2.0/token";
                HttpClient client = new HttpClient();
                List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
                paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
                paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));

                HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
                String result = response.Content.ReadAsStringAsync().Result;

                JObject ResObj = JsonHelper.DeserializeJsonToObject<JObject>(result);
                if (string.IsNullOrEmpty(Convert.ToString(ResObj.GetValue("access_token"))))
                {
                    Globals.Debuglog("---獲取身份驗證access_token失敗:" + result, "_IdentifyCard.txt");
                    return Token;
                }
                HiCache.Insert("access_token", ResObj.GetValue("access_token"), 2592000);  //access_toke 時效30天,需設置緩存從新獲取
                Token = ResObj.GetValue("access_token").ToString();
            }
            return Token;
        }

        /// <summary>
        /// 根據access_token獲取身份證信息
        /// </summary>
        /// <param name="path"></param>
        /// <param name="cardside">身份證正反面(front-正面,back-反面)</param>
        /// <param name="IsDelFile">是否刪除圖片</param>
        /// <returns></returns>
        public static string idcard(string path,string cardside,bool IsDelFile, out string outError)
        {
            outError = string.Empty;
            string token = GetbaiduAccessToken();
            if (!string.IsNullOrEmpty(token))
            {
                try
                {
                    string ext = Path.GetExtension(path).ToLower(); ;
                    if (!ext.Equals(".jpg")  && !ext.Equals(".png") && !ext.Equals(".bmp"))
                    {
                        outError = "識別的圖片僅支持(jpg、png、bmp)格式";
                        return "";
                    }
                    string strbaser64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(path));
                    string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + token;
                    Encoding encoding = Encoding.Default;
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
                    request.Method = "post";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.KeepAlive = true;
                    String str = "id_card_side="+ cardside + "&image=" + HttpUtility.UrlEncode(strbaser64);
                    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 StrResult = Getcardinfo(result, cardside,out outError);
                    if (IsDelFile)
                    {
                        File.Delete(path);
                    }
                    return StrResult;
                }
                catch (Exception)
                {
                    outError = "識別異常!";
                    File.Delete(path);
                }
            }
            return "";

        }

        /// <summary>
        /// 對返回的身份信息進行打包確認
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Getcardinfo(string str,string cardside,out string outError)
        {
            outError = string.Empty;
            JObject Obj = JsonHelper.DeserializeJsonToObject<JObject>(str);
            string status = Convert.ToString(Obj.GetValue("image_status"));
            string strResult = "";
            if (status == "normal")
            {
                if (cardside == "front")
                {
                    IdentifyInfo info = new IdentifyInfo();
                    info.Address = Obj["words_result"]["住址"]["words"].ToString();
                    info.DataBirth = Obj["words_result"]["出生"]["words"].ToString();
                    info.UserName = Obj["words_result"]["姓名"]["words"].ToString();
                    info.IdCard = Obj["words_result"]["公民身份號碼"]["words"].ToString();
                    info.Sex = Obj["words_result"]["性別"]["words"].ToString();
                    info.FamousFamily = Obj["words_result"]["民族"]["words"].ToString();
                    strResult = JsonHelper.SerializeObject(info);
                }
                else
                { strResult = str; }
            }
            else
            {
                switch (status)
                {
                    case "reversed_side":outError = "未擺正身份證!";break;
                    case "non_idcard": outError = "上傳的圖片不是身份證!"; break;
                    case "blurred": outError = "身份證模糊!"; break;
                    case "over_exposure": outError = "身份證關鍵字段反光或過曝!"; break;
                    default: outError = cardside == "front" ? "請正確上傳身份證正面!": "請正確上傳身份證背面!"; break;
                }
            }
            return strResult;
        }
     /// <summary>
        /// 建立臨時地址文件
        /// </summary>
        /// <returns></returns>
        private static string GetPath()
        {
            string path = "";
            try
            {
                path = HttpContext.Current.Request.MapPath("~/Identify");
            }
            catch (Exception e)
            {
                path = Utils.ApplicationPath + "/Identify";
            }

            if (!FileHelper.FileExists(path))
            {
                Directory.CreateDirectory(path);
            }
            path += "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + CommonHelper.RandomNum(4);
            //if (!FileHelper.FileExists(path))
            //{
            //    Directory.CreateDirectory(path);
            //}
            return path;
        }
    [Serializable]
    public class IdentifyInfo
    {
        public string Address { get; set; }

        public string DataBirth { get; set; }

        public string UserName { get; set; }

        public string IdCard { get; set; }

        public string Sex { get; set; }

        //名族
        public string FamousFamily { get; set; }

    }

 

第二款是祥雲科技的OCR雲服務平臺,這裏的識別更精確一點,可是消費有點貴。API文檔:http://www.netocr.com/developers.do?id=4緩存

     /// <summary>
        /// 上傳圖片到翔雲進行身份證識別
        /// </summary>
        /// <param name="filePath">要上傳的文件路徑</param>
        /// <returns></returns>
        public string PostIdCardDataToXiangYun(string filePath)
        {
            string url = "http://netocr.com/api/recog.do";
            System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
            httpClient.MaxResponseContentBufferSize = 256000;
            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            System.Net.Http.MultipartFormDataContent content = new System.Net.Http.MultipartFormDataContent();
            //增長文件數據
            content.Add(new System.Net.Http.StreamContent(fileStream), "file", "idcard.jpg");
            //增長參數
            content.Add(new StringContent("key************"), "key");
            content.Add(new StringContent("secret**********"), "secret");
            //二代身份證正面識別
            content.Add(new StringContent(CardStatus.TwoIdentityCardsFront.ToString()), "typeId");
            content.Add(new StringContent("json"), "format");
            System.Net.Http.HttpResponseMessage response = httpClient.PostAsync(new Uri(url), content).Result;
            string result = response.Content.ReadAsStringAsync().Result;
            fileStream.Close();
            return result;
        }
相關文章
相關標籤/搜索