记录一下在Laravel8项目开发过程中调取腾讯云文字识别OCR
1.获取腾讯云开发秘钥
https://console.cloud.tencent.com/cam/capi
2.在项目env文件中配置SecretId和SecretKey
php
# 腾讯云api
TENCENT_SECRET_ID = 腾讯云SecretId
TENCENT_SECRET_KEY = 腾讯云SecretKey
3.安装腾讯云OCR扩展
php
composer require tencentcloud/ocr
在vendor扩展文件夹下可见新安装的扩展
4.查看腾讯云文字识别OCR文档,对照方法参数进行调取
https://cloud.tencent.com/document/product/866/33526#1.-.E6.8E.A5.E5.8F.A3.E6.8F.8F.E8.BF.B0
对照项目扩展文件夹
5.方法调取
php
<?php
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Ocr\V20181119\Models\GeneralAccurateOCRRequest;
use TencentCloud\Ocr\V20181119\OcrClient;
class IdentifyImageLogic extends Logic
{
/**
* 文字识别
* @param string $file_path 文件相对路径
* @param string $imageBase64 图片base64转码
* @return void
*/
public function identifyImage(string $file_path = '', string $imageBase64 = '')
{
// 判断文件类型
if ($file_path) {
$local_path = storage_path("app/" . $file_path);
$params = array(
// 获取图片的base64加密内容
'ImageBase64' => base64_encode(file_get_contents($local_path)),
);
} else if ($imageBase64) {
$params = array(
// 获取图片的base64加密内容
'ImageBase64' => $imageBase64,
);
} else {
return ['文件不存在', []];
}
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的 方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
$SecretId = env('TENCENT_SECRET_ID');
$SecretKey = env('TENCENT_SECRET_KEY');
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
$cred = new Credential($SecretId, $SecretKey);
// 实例化一个http选项,可选的,没有特殊需求可以跳过
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("ocr.tencentcloudapi.com");
// 实例化一个client选项,可选的,没有特殊需求可以跳过
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
// 实例化要请求产品的client对象,clientProfile是可选的
$client = new OcrClient($cred, "", $clientProfile);
// 实例化一个请求对象,每个接口都会对应一个request对象
$req = new GeneralAccurateOCRRequest();
$req->fromJsonString(json_encode($params));
// 返回的resp是一个GeneralAccurateOCRResponse的实例,与请求对象对应
$resp = $client->GeneralAccurateOCR($req);
// 输出json格式的字符串回包
$list = json_decode($resp->toJsonString())->TextDetections ?? [];
$question_text = [];
foreach ($list as $val) {
$question_text[] = $val->DetectedText ?? '';
}
$question_text_str = implode(PHP_EOL, $question_text);
return ['', ['question_text' => $question_text_str]];
}
}
返回结果按照实际使用要求进行处理,这里只提取了文字部分并且使用换行符分隔。
php
{
"code": 200,
"message": "操作成功",
"data": {
"question_text": "1.驾驶机动车在没有中心线的城市道路上,最高速度不能超过每小时\r\n多少公里?\r\nA. 30 B. 40\r\nC. 50\r\nD.70\r\n答案:A\r\n2.车辆在山区道路跟车行驶时,应怎样做?\r\nA.紧随前车之后\r\nB.适当加大安全距离\r\nC.适当减小安全距离\r\nD.尽可能寻找超车机会\r\n答案:B\r\n3.夜间驾驶机动车通过人行横道时需要交替使用远近光灯。\r\nA. 正确 B. 错误\r\n答案:A"
},
"timestamp": 1751504861779
}
6.扩展中还有其他方法根据实际使用需求进行方法调取