Skip to content

Instantly share code, notes, and snippets.

@johnidm
Last active February 5, 2025 13:18
Show Gist options
  • Save johnidm/f154448e4140d88e8d45a7a1a2107eac to your computer and use it in GitHub Desktop.
Save johnidm/f154448e4140d88e8d45a7a1a2107eac to your computer and use it in GitHub Desktop.
PHP - Using Google Cloud Vision AI

Using Google Cloud Vision AI to perform OCR tasks in PHP

Install the dependence: composer require google/cloud-vision.

You may need to install the OS dependency: sudo apt install php-bcmath.

Using offical PHP Google Cloud Vision library
<?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.";
}
Using HTTP REST request

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.";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment