安卓使用百度云实现身份证识别-之

本文介绍了如何通过百度智能云的文字识别服务来识别身份证,包括获取access_token的步骤以及调用识别接口的示例代码,包括封装请求和传递图像数据的过程。
摘要由CSDN通过智能技术生成

文字识别控制台 【可以领取免费的额度】 百度智能云-登录

百度云 -- key---密钥

百度智能云-登录

通过密钥 和 key 获取 access_token

https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu

调用文字识别接口文档

https://ai.baidu.com/ai-doc/OCR/fk3h7xu7h

识别身份证的示例代码

1. 获取access_token

封装请求接口,其他地方调用就得到了access_token 

//    封装一个百度云获取识别 的access_token  的方法
    public static Map getAccessToken() throws IOException{
        Map mapRes = null;
        MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType ,"");
    Request request = new Request.Builder()
            .url(获取token的请求地址+"?client_id="+百度云的key+"&client_secret="+百度云的Secret_Key+"&grant_type=client_credentials")
            .post(body)
            .addHeader("Content-Type", "application/json")
            .addHeader("Accept", "application/json")
            .build();
    Response response = null;
    try {
        response = client.newCall(request).execute();
        String res = response.body().string();
        if(response.code()==500){
            Log.e("失败请求","详细打印---请求结果"+response);
        }
        resmap = gson.fromJson(res,Map.class);

        Constant.access_token =  resmap.get("access_token").toString();
        System.out.println("token"+Constant.access_token);
        return resmap;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return resmap;
}

2.调用接口传递数据,获取识别内容【参考教程文档】

 1.封装请求接口

    //    封装一个获取识别身份证的接口 方法
    public static JSONObject getCardDetail(String url, Map<String,Object> map) throws IOException{
        JSONObject jsonObject = null;
// 添加这个是为了解决一个报错信息,具体忘记了,
        OkHttpClient client3 = new OkHttpClient.Builder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        // 使用 FormBody.Builder 构建请求体
        FormBody.Builder formBuilder = new FormBody.Builder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            // 将Object转换为String
            String value = (entry.getValue() != null) ? entry.getValue().toString() : "";
            formBuilder.add(entry.getKey(), value);
        }
        RequestBody formBody = formBuilder.build();
        Request request = new Request.Builder()
                .url(Constant.ocrBaseUrl+url+"?access_token="+Constant.access_token)
                .post(formBody)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
//                .post(body)
                .build();
        Log.d("发送请求", "请求参数: "+"\r\n" + formBody.toString());
        Response response = null;
        try {
            response = client3.newCall(request).execute();
            String res = response.body().string();
            Log.d("获取", "response: " + response);

            if(response.code()==500){
                Log.e("失败请求","详细打印---请求结果"+response);
            }
            resmap = gson.fromJson(res,Map.class);
            jsonObject = new JSONObject(resmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;

    }

2. 传递数据-》请求接口-》获取识别数据

身份证识别 - 文字识别OCR

选择照片
 Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
 intent.addCategory(Intent.CATEGORY_OPENABLE);
 intent.setType("image/*");
 startActivityForResult(intent, CHOOSE_PHOTO);
 isImage0 = true;

String base64;

选择完照片得到uri,自己会触发一个事件
 protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode){
            case CHOOSE_PHOTO:
                Uri uri = data.getData();
                try {
                    if(resultCode == Activity.RESULT_OK){
  
//                        通过uri得到base64
                        InputStream inputStream = getContentResolver().openInputStream(uri);
                        byte[] buffer = new byte[inputStream.available()];
                        inputStream.read(buffer);
                        inputStream.close();
                        base64 =  Base64.encodeToString(buffer, Base64.DEFAULT);
//                      封装的 调用处理图片的接口方法
                        getfRrontDetail();
          
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            default:
                break;
        }
    }


//    封装获取前面详情
    public void getfRrontDetail(){
        new Thread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void run() {
                try {
// 获取token
                    getAccessToken();
                    Map<String, Object> params = new HashMap<>();
                    params.put("id_card_side", "front");
                    params.put("image",   base64);
                    params.put("detect_card", false);
                    params.put("detect_risk", true);
                    params.put("detect_quality", true);
                    params.put("detect_photo", false);
                    params.put("detect_direction", false);
                    Map res = null;
                    res = RequestUtil.getCardDetail(Constant.onCardAPI,params);
                    System.out.println("获得身份证结果 "+res);


                    JSONObject res = null;
                    res = RequestUtil.getCardDetail(Constant.onCardAPI,params);
                    JSONObject wordsResult = res.getJSONObject("words_result");
                    System.out.println("获得身份证结果 "+wordsResult);
//                    正面
                   //   wordsResult.getJSONObject("姓名").getString("words")  这个拿到姓名
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值