最近有個需求需要識別圖片中的文字,所以就用到了百度的ocr接口,結果在測試的過程中被圖片格式搞的有點暈,試了好久終於成功了,在此記錄一下。
附ocr接口文檔地址:https://cloud.baidu.com/doc/OCR/OCR-API.html#.E8.BF.94.E5.9B.9E.E8.AF.B4.E6.98.8E
我們先來看一下接口說明:
這里我們主要來看圖片參數,圖片參數可以通過兩種方式傳遞:
- url方式
通過url傳遞比較簡單,直接拿過來用就好,實例代碼如下:
<?php
function request_post($url = '', $param = '', $header = []) {
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
$curl = curl_init();//初始化curl
curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定網頁
curl_setopt($curl, CURLOPT_HEADER, 0);//設置header
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求結果為字符串且輸出到屏幕上
curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($curl);//運行curl
curl_close($curl);
return $data;
}
$api = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=xxxxxxx';
$image_url = 'xxx.com/a.png'; // 網絡圖片url
$header = ['Content-Length: application/x-www-form-urlencoded'];
$post = [
'url' => $image_url,
];
$res = request_post($api, $post, $header);
2、image方式
image參數需要對本地圖片進行base64編碼,然后進行傳遞,接口文檔中比較坑的點:
- Content-Type用的是multipart/form-data
- base64編碼后並不需要進行urlencode
$api = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=xxxxxxx';
$header = ['Content-Length: multipart/form-data'];
$file = '/data/image/a.png'; // 本地圖片路徑
$image = base64_encode(file_get_contents($file));
$post = [
'image' => $image,
];
$res = request_post($api, $post, $header);