Closed
Description
自行实现文字识别API的调用,首先需要将要识别的图片上传到阿里云的上海oss,得到上传的图片得到的oss对象的url,参考代码如下
use OSS\OssClient;
……
$accessKeyId = 'your access key id for oss';
$accessKeySecret = 'your access key secret for oss';
$bucket = 'the bucket you use';
$endpoint = 'oss-cn-shanghai.aliyuncs.com';
$objectPath = 'path used in oss bucket for your file';
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$ossClient->uploadFile($bucket, $objectPath, 'absolute path of the file that you want to recognize character from');
// $ossClient->deleteObject($bucket, $objectPath);
} catch (Exception $e) {
throw new Exception("Failed to upload file for recognizing character. Exception message is " . $e->getMessage());
}
$fileOssUrl = 'https://' . $bucket . '.' . $endpoint . '/' . $objectPath;
然后生成调用文字识别API所需的签名,使用包含上边得到的oss对象url在内的若干参数,调用文字识别API(使用了GuzzleHttp)
use GuzzleHttp\Client;
……
$accessKeyId = 'your access key id for ocr';
$accessKeySecret = 'your access key secret for ocr';
$params = [
'SignatureMethod' => 'HMAC-SHA1',
'SignatureNonce' => md5(microtime(true)),
'AccessKeyId' => $accessKeyId,
'SignatureVersion' => '1.0',
'Timestamp' => (new DateTime('now', new DateTimeZone('GMT')))->format("Y-m-d\\TH:i:s\\Z"),
'Format' => 'JSON',
'RegionId' => 'cn-shanghai',
'Version' => '2019-12-30',
'Action' => 'RecognizeCharacter',
'ImageURL' => $fileOssUrl,
'MinHeight' => 5,
'OutputProbability' => 'true',
];
ksort($params);
$paramsStr = '';
foreach ($params as $key => $value) {
$paramsStr .= '&' . $this->encodeForSignature($key) . '=' . $this->encodeForSignature($value);
}
$paramsStr = substr($paramsStr, 1);
$strToSign = 'POST&' . $this->encodeForSignature('/') . '&' . $this->encodeForSignature($paramsStr);
$signature = $this->encodeForSignature(base64_encode(hash_hmac('sha1', $strToSign, $accessKeySecret . '&', true)));
try {
$client = new Client();
$response = $client->post("https://ocr.cn-shanghai.aliyuncs.com?Signature={$signature}&{$paramsStr}");
if ($response->getStatusCode() == 200) {
$apiResult = json_decode($response->getBody()->getContents(), true);
}
} catch (Exception $e) {
}
如果在得到文字识别结果之后,希望删除oss中的对象,使用第一段示例代码中注释掉的代码即可
Metadata
Metadata
Assignees
Labels
No labels