OCR智能识别身份信息

本人研究了两款OCR智能识别的API,下面做详解!

第一款是百度云的OCR识别,填写配置信息,每天有五百次免费的识别次数,适合中小型客户流量可以使用。API文档:http://ai.baidu.com/docs#/OCR-API/top

     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;
        }

 

posted @ 2017-06-15 17:56  渴死的鱼丶  阅读(588)  评论(3编辑  收藏  举报