config->load('qiniu', true, true); $qiniu_config = $CI->config->item('qiniu'); $this->config = $qiniu_config['img']; } } /** * 保险单识别 * @param $img_url 图片url地址 * @return array */ public function car_insure($img_url){ // $img_url = "https://img.liche.cn/liche/liche/202204/p_c7ea3a764339e41539625e33f3f2ac37.jpg"; $file_base64 = $this->imgtobase64($img_url); $body=json_encode(['image'=>$file_base64]); $url = self::CAR_URL; $host="ocr-car-bd.qiniuapi.com"; $method='POST'; $header = $this->header($url,$method,$body); $header['Content-type']= 'application/json'; $header['Host']= $host; $head=[]; foreach($header as $k=>$v){ $head[]=$k.':'.$v; } $result=$this->post_json_data($url,$body,$head); $data = json_decode($result,true); if(!$data['errorcode'] && $data['items']['保险公司']!='None'){ $res = ['code' => 1 ,'msg' => '识别成功','data'=>$data['items']]; }else{ $msg = $data['errorcode'] ? $data['errormsg'] : ''; debug_log("识别图片地址:".$img_url,$this->log_file); debug_log("识别结果:".json_encode($data,JSON_UNESCAPED_UNICODE),$this->log_file); $res = ['code' => 0 ,'msg'=>'识别失败:'.$msg]; } return $res; } private function header($url,$method,$body,$contentType = "application/json"){ // 需要填写你的 Access Key 和 Secret Key $accessKey = $this->config['access_key']; $secretKey = $this->config['secret_key']; // 构建鉴权对象 $auth = new \Qiniu\Auth($accessKey, $secretKey); $header=$auth->authorizationV2($url,$method,$body,$contentType); return $header; } function post_json_data($url, $data_string,$aHeader,$timeout=300) { if(!$aHeader){ $length=strlen($data_string); $aHeader= array('Content-type:application/json', 'Content-length:'.$length); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //设置头文件的信息作为数据流输出 //curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader); // post数据 curl_setopt($ch, CURLOPT_POST, true); // post的变量 curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); $file_contents = curl_exec($ch); curl_close($ch); return $file_contents; } /** * 把网络图片图片转成base64 * @param $url 图片url地址 * @return void */ public function imgtobase64($url){ $stream_opts = [ "ssl" => [ "verify_peer"=>false, "verify_peer_name"=>false, ] ]; $img = file_get_contents($url,false,stream_context_create($stream_opts)); $temp_path = FCPATH.'temp/'.time().rand(100000,999999).'jpg'; file_put_contents($temp_path,$img); $base64 = ''; if($fp = fopen($temp_path,"rb", 0)) { $gambar = fread($fp,filesize($temp_path)); fclose($fp); $base64 = chunk_split(base64_encode($gambar)); } @unlink($temp_path); return $base64; } }