Android studio Android集成百度身份证识别 详细步骤

最近因为项目需要,进行了集成百度身份证识别的验证damo;

很多地方都是按照官方的来的,能力强的小伙伴可以直接看官方damo;


一,创建项目,并下载SDK


1>去百度大脑处注册账号并创建项目,地址:https://ai.baidu.com/

    1.1点击控制台,进入管理中心



1.2 进入管理中心后,点击左侧产品服务,选择文字识别



1.3 进入文字识别概览,选择创建应用,点击立即创建



1.4 按照要求填好资料,出于安全考虑还是绑定包名



1.4提示创建成功后点击 下载SDK



1.5下载 文字识别里的Android SDK



二,集成SDK

2.1 把包内的libs文件下的所有文件放入Android Stuio项目中的libs里

当然ocr-sdk.jar包记得 右键add as library


由于个人习惯的原因,官方要求的是放到jnilibs 我没有按照官方要求的做,所以还要在build.gradle里添加以下代码

sourceSets {
        main {
            jniLibs.srcDir(['libs'])
        }
    }


2.2 把orc_ui文件以模块方式导入到项目里



2.3 引入后还有最后一步,把授权文件aip.license放入到assets目录中,这步很重要,不做会导致授权失败,无法识别

授权文件 aip.license在这个位置下载




三,代码实现


首先是布局


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_idcard"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.baiduidcard.MainActivity">

<Button
    android:text="相册选择 正面"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/gallery_button_front"
    tools:ignore="HardcodedText"/>

<Button
    android:text="相册选择 反面"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/gallery_button_back"
    tools:ignore="HardcodedText"/>

<Button
    android:id="@+id/id_card_front_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="身份证正面"
    tools:ignore="HardcodedText" />

<Button
    android:id="@+id/id_card_back_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="身份证反面"
    tools:ignore="HardcodedText" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="姓名"
        android:gravity="center"/>

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="20dp" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="性别"
        android:gravity="center"/>

    <TextView
        android:id="@+id/tv_gender"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="20dp"/>

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="民族"
        android:gravity="center"/>

    <TextView
        android:id="@+id/tv_ethnic"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="20dp" />
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="生日"
        android:gravity="center"/>

    <TextView
        android:id="@+id/tv_birthday"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="20dp"/>

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="住址"
        android:gravity="center"/>

    <TextView
        android:id="@+id/tv_address"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="20dp" />
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="身份证号"
        android:gravity="center"/>

    <TextView
        android:id="@+id/tv_idNumber"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="20dp"/>

</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="签发机关"
        android:gravity="center"/>

    <TextView
        android:id="@+id/tv_issueAuthority"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="20dp"/>

</LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="有效期限"
        android:gravity="center"/>

    <TextView
        android:id="@+id/tv_youxiaodate"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="20dp"/>

</LinearLayout>

</LinearLayout>


然后是Mainactivity

package com.example.administrator.baiduidcard;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;


import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_PICK_IMAGE_FRONT = 201;
    private static final int REQUEST_CODE_PICK_IMAGE_BACK = 202;
    private static final int REQUEST_CODE_CAMERA = 102;
    private AlertDialog.Builder alertDialog;
    private TextView tv_name,tv_gender,tv_ethnic,tv_birthday,tv_address,tv_idNumber,tv_issueAuthority,tv_youxiaodate;

    private boolean checkGalleryPermission() {
        int ret = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission
                .READ_EXTERNAL_STORAGE);
        if (ret != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
                    1000);
            return false;
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        alertDialog = new AlertDialog.Builder(this);

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_gender = (TextView) findViewById(R.id.tv_gender);
        tv_ethnic = (TextView) findViewById(R.id.tv_ethnic);
        tv_birthday = (TextView) findViewById(R.id.tv_birthday);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_idNumber = (TextView) findViewById(R.id.tv_idNumber);
        tv_issueAuthority = (TextView) findViewById(R.id.tv_issueAuthority);
        tv_youxiaodate = (TextView) findViewById(R.id.tv_youxiaodate);

        findViewById(R.id.gallery_button_front).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkGalleryPermission()) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE_FRONT);
                }
            }
        });

        findViewById(R.id.gallery_button_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkGalleryPermission()) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE_BACK);
                }
            }
        });

        findViewById(R.id.id_card_front_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
            }
        });

        findViewById(R.id.id_card_back_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
            }
        });

        OCR.getInstance().initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                // 调用成功,返回AccessToken对象
                String token = result.getAccessToken();
            }
            @Override
            public void onError(OCRError error) {
                // 调用失败,返回OCRError子类SDKError对象
            }
        }, getApplicationContext());
    }

    private void recIDCard(final String idCardSide, String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        param.setIdCardSide(idCardSide);
        param.setDetectDirection(true);
        OCR.getInstance().recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                if (result != null) {
                    if (idCardSide.equals("front")){
                        tv_name.setText(result.getName().toString());
                        tv_gender.setText(result.getGender().toString());
                        tv_ethnic.setText(result.getEthnic().toString());
                        tv_birthday.setText(result.getBirthday().toString());
                        tv_address.setText(result.getAddress().toString());
                        tv_idNumber.setText(result.getIdNumber().toString());
                    }else if (idCardSide.equals("back")){
                        tv_issueAuthority.setText(result.getIssueAuthority().toString());
                        tv_youxiaodate.setText(result.getSignDate()+"-"+result.getExpiryDate());
                    }
                }
            }

            @Override
            public void onError(OCRError error) {
                alertText("", error.getMessage());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE_FRONT && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String filePath = getRealPathFromURI(uri);
            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
        }

        if (requestCode == REQUEST_CODE_PICK_IMAGE_BACK && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String filePath = getRealPathFromURI(uri);
            recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
        }

        if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                String filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
                if (!TextUtils.isEmpty(contentType)) {
                    if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
                    } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
                    }
                }
            }
        }
    }

    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                alertDialog.setTitle(title)
                        .setMessage(message)
                        .setPositiveButton("确定", null)
                        .show();
            }
        });
    }

    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }
}


还有个FileUtil工具类

/*
 * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
 */
package com.example.administrator.baiduidcard;

import android.content.Context;

import java.io.File;

public class FileUtil {
    public static File getSaveFile(Context context) {
        File file = new File(context.getFilesDir(), "pic.jpg");
        return file;
    }
}



以上就是全部代码,有错误还望指正,转发请注明出处!



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值