In today's digital age, Optical Character Recognition (OCR) technology is widely used across various industries. OCR technology allows you to convert text from images into editable content, greatly improving data processing efficiency and accuracy. As a PHP developer, combining Alibaba Cloud OCR and image processing capabilities enables easy image recognition and text extraction. This article will explain how to use PHP with Alibaba Cloud OCR and image processing to perform text recognition and subsequent image processing.
composer require aliyuncs/ocr composer require aliyuncs/imagesearch
Then, use Composer's autoloader:
require_once 'vendor/autoload.php';
use AlibabaCloud\Client\AlibabaCloud; use AlibabaCloud\Client\Exception\ClientException; use AlibabaCloud\Client\Exception\ServerException; AlibabaCloud::accessKeyClient('your-access-key-id', 'your-access-key-secret') ->regionId('cn-hangzhou') ->asDefaultClient();
Now, call the OCR API to recognize text from an image:
use AlibabaCloud\Ocr\Ocr; try { $result = Ocr::v20191230() ->ocr() ->withImageUrl('your-image-url') ->withType('businessCard') ->request(); print_r($result); } catch (ClientException $e) { echo $e->getErrorMessage(); } catch (ServerException $e) { echo $e->getErrorMessage(); }
Specify the image URL using withImageUrl and the recognition type (e.g., ID card, business card, etc.) with withType. Once successful, the result will contain the recognized text.
use AlibabaCloud\Client\AlibabaCloud; use AlibabaCloud\Client\Exception\ClientException; use AlibabaCloud\Client\Exception\ServerException; AlibabaCloud::accessKeyClient('your-access-key-id', 'your-access-key-secret') ->regionId('cn-hangzhou') ->asDefaultClient();
Now, call the image processing API:
use AlibabaCloud\Imageprocess\Imageprocess; try { $result = Imageprocess::v20200320() ->analyzeImage() ->withImageUrl('your-image-url') ->request(); print_r($result); } catch (ClientException $e) { echo $e->getErrorMessage(); } catch (ServerException $e) { echo $e->getErrorMessage(); }
Specify the image URL using withImageUrl. After processing, the result will include analysis information, such as face detection or object recognition.
use AlibabaCloud\Client\AlibabaCloud; use AlibabaCloud\Client\Exception\ClientException; use AlibabaCloud\Client\Exception\ServerException; use AlibabaCloud\Ocr\Ocr; AlibabaCloud::accessKeyClient('your-access-key-id', 'your-access-key-secret') ->regionId('cn-hangzhou') ->asDefaultClient(); try { $result = Ocr::v20191230() ->ocr() ->withImageUrl('your-image-url') ->withType('businessCard') ->request(); $cards = $result['Data']['cards']; foreach ($cards as $card) { $phoneNumber = $card['phoneNumber']; echo "Phone Number: $phoneNumber"; } } catch (ClientException $e) { echo $e->getErrorMessage(); } catch (ServerException $e) { echo $e->getErrorMessage(); }
The above code extracts the phone number from the business card image and prints it. You can further process the extracted phone number as needed.