百度Ocr身份证识别

 controller代码

 //可以写入配置文件
    String clientId = "去百度云注册账号获取";
    // 官网获取的 Secret Key 更新为你注册的
    String clientSecret = "去百度云注册账号获取";

    /**
     * 身份证正面
     * @return
     */
    @GetMapping("/IdCard/front/{uid}")
    @ApiOperation(value = "身份证正面")
    public IdCard idCardFront(@PathVariable(name = "uid")int uid){
        //Token有效期为30天 2592000秒 可以将token存入redis避免重复获取,也可以每次请求获取
        String Token =authService.getAuth(clientId,clientSecret);
        //filePath 为本地身份证地址 需要从数据库查询
        PmsPhoto pmsPhoto = pmsPhotoService.selectPmsPhotoById(uid);
        //拿到百度返回的json串
        String idcardResult = idcardService.idcard(pmsPhoto.getIdcardFrontBig(),Token);
        //将json串转化成类
        IdCard idcard = jsonService.getIdcardFront(idcardResult);
        PmsUser pmsUser=new PmsUser();
        //copy对象
        BeanUtils.copyProperties(idcard, pmsUser);
        pmsUser.setId(uid);
        pmsUserService.updatePmsUser(pmsUser);
        return idcard;
    }

获取Ocr权限 authService  获取Token

 /**
     * 获取API访问token
     * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Secret Key
     * @return assess_token 示例:
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new  InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }

idcardService根据百度ocr示例代码进行修改,param参数可以根据百度Ocr示例参数进行自定义

  // 请求url
    static String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";

    // aes key 从console控制台获取
    static String aesKey = "454872cbcd90a105";

    static byte[] originAesKey = null;

    public static String idcard(String filePath,String Token) {
        try {
            // 本地文件路径
//            String filePath = "D:\\a\\hyy.jpg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            //加密图片
            String imgStr = encryptImg(aesKey, imgData);

            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "id_card_side=" + "front" +
                    "&image=" + imgParam +
                    "&AESEncry=" + true ;

            String encryptResult = HttpUtil.post(url, Token, param);
            //解密图片
            String decryptResult = parseResult(encryptResult);

            return decryptResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
jsonService 从百度返回的json数据中取出自己需要的
  public IdCard getIdcardFront(String idcardResult){
                JSONObject words_result =JSONObject.parseObject(idcardResult);
                //从JSONObject中取对应的值
                JSONObject JsonidCard = new JSONObject();
                JsonidCard.put("name", words_result.getJSONObject("words_result").getJSONObject("姓名").get("words"));
                JsonidCard.put("nation", words_result.getJSONObject("words_result").getJSONObject("民族").get("words"));
                JsonidCard.put("address", words_result.getJSONObject("words_result").getJSONObject("住址").get("words"));
                JsonidCard.put("sex", words_result.getJSONObject("words_result").getJSONObject("性别").get("words"));
                JsonidCard.put("birth", words_result.getJSONObject("words_result").getJSONObject("出生").get("words"));
                JsonidCard.put("number", words_result.getJSONObject("words_result").getJSONObject("公民身份号码").get("words"));
                //JSONObject转对象
                IdCard idCard = JSON.toJavaObject(JsonidCard,IdCard.class);
                return idCard;
        }

总结:1.支持本地图片和url

           2.需要Maven依赖和工具类支持,可以从以下文档获取,也可以从官方文档获取

           3.代码仅供参考更详细内容可以参考以下文档:

     (117条消息) Java集成第三方OCR识别——文档篇_Monster_起飞的博客-CSDN博客_java ocr库icon-default.png?t=M85Bhttps://blog.csdn.net/Monsterof/article/details/124428930

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值