阿里云OCR与PHP开发:一个实用的教程示例
composer require alibabacloud/sdk
安装完成后,我们可以创建一个OCR Client,并设置好AccessKeyId和AccessKeySecret:
<?php require_once __DIR__ . '/vendor/autoload.php'; use AlibabaCloudClientAlibabaCloud; use AlibabaCloudClientExceptionClientException; use AlibabaCloudClientExceptionServerException; use AlibabaCloudOcrOcr; // 设置AccessKeyId和AccessKeySecret AlibabaCloud::accessKeyClient('{AccessKeyId}', '{AccessKeySecret}') ->regionId('cn-hangzhou') ->name('default') ->timeout(20) ->connectTimeout(0) ->asGlobalClient(); // 创建OCR Client $client = new Ocr();
接下来,我们就可以使用OCR Client来调用OCR API了。例如,下面的示例代码演示了如何使用OCR API对一张图片进行文字识别:
<?php try { $result = $client->v20191230()->recognizeBusinessCard() ->withImageUrl('https://example.com/image.jpg') ->request(); print_r($result->toArray()); } catch (ClientException $e) { echo $e->getErrorMessage() . PHP_EOL; } catch (ServerException $e) { echo $e->getErrorMessage() . PHP_EOL; }
以上代码实现了对名片图片进行文字识别,并将识别结果打印输出。
business_license.jpg
,我们想要从中提取出公司名称、法定代表人、注册资本等信息。<?php try { $result = $client->v20191230()->recognizeBusinessLicense() ->withImageUrl('https://example.com/business_license.jpg') ->request(); $info = $result->toArray()['data']['config']['tables'][0]['rows']; $companyName = $info[0]['row'][1]['text']; $legalPerson = $info[6]['row'][1]['text']; $registeredCapital = $info[8]['row'][1]['text']; echo '公司名称:' . $companyName . PHP_EOL; echo '法定代表人:' . $legalPerson . PHP_EOL; echo '注册资本:' . $registeredCapital . PHP_EOL; } catch (ClientException $e) { echo $e->getErrorMessage() . PHP_EOL; } catch (ServerException $e) { echo $e->getErrorMessage() . PHP_EOL; }
以上代码通过调用recognizeBusinessLicense
接口,将营业执照图片中的信息提取出来并打印输出。
以上是阿里云OCR与PHP开发:一个实用的教程示例的详细内容。更多信息请关注PHP中文网其他相关文章!