先去百度AI申请开放平台的账号,http://ai.baidu.com、
创建应用,来获取需要的三个参数AppID,API Key,SECRET Key
然后下载我用的是PHP,所以下载PHP的SDK;
将下载的SDK解压,取出lib目录和AipOcr.php放到项目中,(这里有可能要给每个文件添加命名空间)
将AipOcr.php中的idcard方法改了一下,
注意:一定要将图片传到服务器中,然后将路径由根目录拼接或是域名拼接,不然会一直显示216201图片格式错误,这里 我耽误了好长的时间!!!
public function idcard($image, $idCardSide, $options=array()){
$data = array();
$img_file_path = $_SERVER['DOCUMENT_ROOT'].$image;
$file_res = fopen($img_file_path,'r');
$img_content = fread($file_res,filesize($img_file_path));
fclose($file_res);
$data['image'] = base64_encode($img_content);
//得获取项目的根目录路径
//file_get_content不能读取本地图片信息,只能读取一个远程资源,哪个域名
// var_dump(file_get_contents('域名'.$image));die;
$data['id_card_side'] = $idCardSide;
$data = array_merge($data, $options);
return $this->request($this->idcardUrl, $data);
}
里面用file_get_contents(‘域名’.$image)这种方法也行,但是不太友好,还得将域名写进来,看自己需要吧,都能实现!!!
然后是控制器中方法
//身份中识别API
public function shenfenAPI($image)
{
$app_id = '自己的';//AppID
$api_key = '自己的';//API Key
$secret_key = '自己的';//SECRET Key
$client = new AipOcr($app_id, $api_key, $secret_key);
$idCardSide = "front";
$data = $client->idcard($image,$idCardSide);
if($data['error_msg']){
$res['msg'] = '识别失败';
$res['code'] = 201;
$res['data'] = $data;
} else {
$shibie['shenfenhao'] = $data['words_result']['公民身份号码']['words'];
$shibie['xingming'] = $data['words_result']['姓名']['words'];
//var_dump($res);
$res['msg'] = '识别成功';
$res['code'] = 200;
$res['data'] = $shibie;
}
//var_dump($res);
echo json_encode($res);
}
我这里只需要姓名和身份证号!!!