Install the dependence: composer require google/cloud-vision
.
You may need to install the OS dependency: sudo apt install php-bcmath
.
<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Vision\V1\Feature\Type; # composer require google/cloud-vision
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . getenv('GOOGLE_APPLICATION_CREDENTIALS'));
$client = new ImageAnnotatorClient();
$image = file_get_contents('image.jpg');
$response = $client->annotateImage( # $response = $client->textDetection($image);
$image,
[Type::TEXT_DETECTION]
);
$fullText = $response->getFullTextAnnotation();
if ($fullText) {
print $fullText->getText();
} else {
print "No text detected.";
}
Install the dependence: composer require guzzlehttp/guzzle
.
<?php
require __DIR__ . '/vendor/autoload.php';
const API_URL = "https://vision.googleapis.com/v1/images:annotate";
const API_KEY = ""; # Your API key
$client = new \GuzzleHttp\Client; # composer require guzzlehttp/guzzle
$imagePath = 'image.jpg';
$imageContent = file_get_contents($imagePath);
if ($imageContent === false) {
die("Error: Unable to read the file $imagePath");
}
$response = $client->post(API_URL . "?key=" . API_KEY, [
'json' => [
'requests' => [
[
'image' => [
'content' => base64_encode($imageContent)
],
'features' => [
[
'type' => 'TEXT_DETECTION'
]
]
]
]
]
]);
$data = json_decode($response->getBody()->getContents(), true);
$fullText = $data['responses'][0]['fullTextAnnotation']['text'];
if ($fullText) {
print $fullText;
} else {
print "Text not found.";
}