代码展示:
/** * 获取名片信息 * @param string $img_url base64图片路径 */ public function getCardInfo($base_img_url){// $imgbase64 = $img_url; // 修改 解决app base64图片上传错误问题 $base_img_url = str_replace(' ', '+', $base_img_url); $imgbase64 = substr($base_img_url,strpos($base_img_url,',')+1);
$host = "https://dm-57.data.aliyun.com"; $path = "/rest/160601/ocr/ocr_business_card.json"; $method = "POST"; $appcode = "********";//你自己的AppCode $headers = array(); array_push($headers, "Authorization:APPCODE " . $appcode); //根据API的要求,定义相对应的Content-Type array_push($headers, "Content-Type".":"."application/json; charset=UTF-8"); array_push($headers, "Expect:".""); // $querys = ""; $bodys = "{\"inputs\":[{\"image\":{\"dataType\":50,\"dataValue\":\"$imgbase64\"}}]}"; $url = $host . $path; $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); //设置头文件的信息作为数据流输出 curl_setopt($curl, CURLOPT_HEADER, 0); if (1 == strpos("$".$host, "https://")) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); } curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys); $info = curl_exec($curl); if (!$info || $info === 'null'){ $statusCode = 400; $res = array('msg'=>"CURL Error:" . curl_error($curl)); } else { $info = json_decode($info,true); $res['data'] = $info['outputs'][0]['outputValue']['dataValue']; // $res['data'] = $info; $res['img_url'] = $img_url['thumbnail']; } curl_close($curl);
return $res;
// $statusMessage = $this -> getHttpStatusMessage($statusCode); // header('HTTP/1.1'. " ". $statusCode ." ". $statusMessage); // echo $res; }
开发中遇到的问题:
1、阿里接口的图片路径是base64格式,但不是完整路径,需要去掉逗号前面的东西(data:image/jpeg;base64,)
2、在APP中传base64格式时,传递过程中会把字符串里面的+替换为空格,所以需要处理换回来