1. 程式人生 > >印刷文字識別-身份證識別(阿裏雲)

印刷文字識別-身份證識別(阿裏雲)

文件路徑 mob transfer UNC cti subst set header 3.2

以下是自己根據阿裏雲api文檔說明封裝的工具類,主要是獲取阿裏雲Oss身份證圖片信息

阿裏雲api文檔URL:https://market.aliyun.com/products/57124001/cmapi010401.html?spm=a2c4g.11186623.2.7.VojbRu

<?php

namespace Helper;

use org\Response;
use think\Controller;
use think\Request;
use think\Db;
use think\Loader;

/**
 * 身份證識別
 * Class AutoRecognition
 * @package app\user\controller
 * @author fgf <2018-06-07>
 
*/ class AutoRecognition { /** * 讀取遠程圖片的二進制流 * @param string $url * @return bool|string */ public static function httpDownload($url=‘‘){ if(empty($url)){ return false; } ob_start(); $contents = @readfile($url); $img = ob_get_contents
(); ob_end_clean(); return $img; } /** * 身份證正面識別 * $file 你的文件路徑 * $param $appcode 阿裏雲APPCODE * @return array */ public static function face($file=‘‘) { if (empty($file)) { return Response::response(1,‘圖片為空‘); }
//請求阿裏雲api地址 $url = "https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json"; $appcode = config(‘APPCODE‘);//讀取配置文件阿裏雲APPCODE //你的文件路徑 //$file = "你的文件路徑"; //如果輸入帶有inputs, 設置為True,否則設為False $is_old_format = false; //如果沒有configure字段,config設為空 $config = array( "side" => "face"//身份證正反面類型:face/back ); //$config = array() //打開文件 if($fp = @fopen($file, "rb", 0)) { //$binary = fread($fp, filesize($file)); // 文件讀取-filesize無法獲取遠程文件的大小,只能讀取path路徑文件 $binary = self::httpDownload($file); // 文件讀取-讀取遠程圖片的二進制流 fclose($fp); $base64 = base64_encode($binary); // 轉碼 }else{ return Response::response(1,‘圖片打開失敗,請檢查圖片路徑是否正確‘); } $headers = array(); array_push($headers, "Authorization:APPCODE " . $appcode); //根據API的要求,定義相對應的Content-Type array_push($headers, "Content-Type".":"."application/json; charset=UTF-8"); $querys = ""; if($is_old_format == TRUE){ $request = array(); $request["image"] = array( "dataType" => 50, "dataValue" => "$base64" ); if(count($config) > 0){ $request["configure"] = array( "dataType" => 50, "dataValue" => json_encode($config) ); } $body = json_encode(array("inputs" => array($request))); }else{ $request = array( "image" => "$base64" ); if(count($config) > 0){ $request["configure"] = json_encode($config); } $body = json_encode($request); } $method = "POST"; $curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_FAILONERROR, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, true); if (1 == strpos("$".$url, "https://")) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); } curl_setopt($curl, CURLOPT_POSTFIELDS, $body); $result = curl_exec($curl); $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $rheader = substr($result, 0, $header_size); $rbody = substr($result, $header_size); $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE); if($httpCode == 200){ if($is_old_format){ $output = json_decode($rbody, true); $result_str = $output["outputs"][0]["outputValue"]["dataValue"]; }else{ $result_str = $rbody; } //printf("result is :\n %s\n", $result_str);//這是阿裏原生的結果打印 //身份證讀取內容輸出 return Response::response(0, json_decode($result_str)); }else{ printf("Http error code: %d\n", $httpCode); printf("Error msg in body: %s\n", $rbody); printf("header: %s\n", $rheader); } } /** * 身份證反面識別 * $param $file 你的文件路徑 * $param $appcode 阿裏雲APPCODE * @param string $file */ public static function back($file=‘‘) { if (empty($file)) { return Response::response(1,‘圖片為空‘); } //請求阿裏雲api地址 $url = "https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json"; $appcode = config(‘APPCODE‘);//讀取配置文件阿裏雲APPCODE //你的文件路徑 //$file = "你的文件路徑"; //如果輸入帶有inputs, 設置為True,否則設為False $is_old_format = false; //如果沒有configure字段,config設為空 $config = array( "side" => "back"//身份證正反面類型:face/back ); //$config = array() //打開文件 if($fp = @fopen($file, "rb", 0)) { //$binary = fread($fp, filesize($file)); // 文件讀取-filesize無法獲取遠程文件的大小,只能讀取path路徑文件 $binary = self::httpDownload($file); // 文件讀取-讀取遠程圖片的二進制流 fclose($fp); $base64 = base64_encode($binary); // 轉碼 }else{ return Response::response(1,‘圖片打開失敗,請檢查圖片路徑是否正確‘); } $headers = array(); array_push($headers, "Authorization:APPCODE " . $appcode); //根據API的要求,定義相對應的Content-Type array_push($headers, "Content-Type".":"."application/json; charset=UTF-8"); $querys = ""; if($is_old_format == TRUE){ $request = array(); $request["image"] = array( "dataType" => 50, "dataValue" => "$base64" ); if(count($config) > 0){ $request["configure"] = array( "dataType" => 50, "dataValue" => json_encode($config) ); } $body = json_encode(array("inputs" => array($request))); }else{ $request = array( "image" => "$base64" ); if(count($config) > 0){ $request["configure"] = json_encode($config); } $body = json_encode($request); } $method = "POST"; $curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_FAILONERROR, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, true); if (1 == strpos("$".$url, "https://")) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); } curl_setopt($curl, CURLOPT_POSTFIELDS, $body); $result = curl_exec($curl); $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $rheader = substr($result, 0, $header_size); $rbody = substr($result, $header_size); $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE); if($httpCode == 200){ if($is_old_format){ $output = json_decode($rbody, true); $result_str = $output["outputs"][0]["outputValue"]["dataValue"]; }else{ $result_str = $rbody; } //printf("result is :\n %s\n", $result_str);//這是阿裏原生的結果打印 //身份證讀取內容輸出 return Response::response(0, json_decode($result_str)); }else{ printf("Http error code: %d\n", $httpCode); printf("Error msg in body: %s\n", $rbody); printf("header: %s\n", $rheader); } } }

工具類在tp5.0中的結構位置如下圖

技術分享圖片

正常返回示例

正面返回結果:
{
    
    "address"    : "浙江省杭州市余杭區文一西路969號",   #地址信息
    "config_str" : "{\\\"side\\\":\\\"face\\\"}",                #配置信息,同輸入configure
    "face_rect":{
        "angle": -90,
        "center":{
            "x" : 952,
            "y" : 325.5
        },
        "size":{
            "height":181.99,
            "width":164.99
            }
    },                          #人臉位置,center表示人臉矩形中心坐標,size表示人臉矩形長寬,angle表示矩形順時針旋轉的度數。
    "name" : "張三",                                  #姓名
    "nationality": "漢", #民族 
    "num" : "1234567890",                             #身份證號
    "sex" : "男",                                     #性別
    "birth" : "20000101",                             #出生日期
    "nationality" : "漢",                             #民族
    "success" : true                                  #識別結果,true表示成功,false表示失敗
}


反面返回結果:
{
    "config_str" : "{\\\"side\\\":\\\"back\\\"}",#配置信息,同輸入configure
    "start_date" : "19700101",       #有效期起始時間
    "end_date" : "19800101",         #有效期結束時間
    "issue" : "杭州市公安局",         #簽發機關
    "success" : true                   #識別結果,true表示成功,false表示失敗
}

使用此工具類可參考如下步驟

1.Controller引入工具類 use Helper\AutoRecognition;

2.

public function save(Request $request)
    {
        $param = $request->only([‘username‘, ‘idnum‘, ‘mobile‘, ‘idcard_a‘, ‘idcard_b‘]);
        $param[‘userid‘] = $this->userid;
        $param[‘status‘] = 0;

        //身份證正面識別
        $res = self::check_idcard_face_message($param);
        if (!$res) {
            return Response::response(1,‘填寫身份證號碼與證件號碼不符‘);
        }
        //身份證反面識別
        $res = self::check_idcard_back_message($param);
//        dump($res);exit;
        if (!$res) {
            return Response::response(1,‘身份證已過期‘);
        }
             

    }

3.

/**
     * 身份證正面信息校對
     * @param $file 身份證正面圖片
     * @return bool
     */
    public static function check_idcard_face_message($param)
    {
        if ($param[‘idcard_b‘]) {
            $file = get_image_url($param[‘idcard_b‘]);
        } else {
            return false;
        }
        //調取阿裏身份認證api獲取身份證信息
        $data =  AutoRecognition::face($file);
        //dump($data);exit;
        if($data[‘data‘]->num == $param[‘idnum‘]){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 身份證反面信息校對
     * @param $file 身份證反面圖片-國徽面
     * @return bool
     */
    public static function check_idcard_back_message($param)
    {
        if ($param[‘idcard_a‘]) {
            $file = get_image_url($param[‘idcard_a‘]);
        } else {
            return false;
        }
        //調取阿裏身份認證api獲取身份證信息
        $data =  AutoRecognition::back($file);
        //dump($data);exit;
        $end_date = $data[‘data‘]->end_date;//提取身份證過期時間
        $y = substr($end_date,0,4);//截取年
        $m = substr($end_date,4,2);//截取月
        $d = substr($end_date,6,2);//截取日
        $last_date_unix = strtotime($y.‘-‘.$m.‘-‘.$d);//身份證截止日時間戳
        $today_unid = strtotime(date(‘Y-m-d‘));//今日時間戳
        //身份證截止日時間戳 > 今日時間戳,身份證未過期,返回true
        if($last_date_unix > $today_unid){
            return true;
        } else {
            return false;
        }
    }

印刷文字識別-身份證識別(阿裏雲)