PHP - google vision API - Class not found

1.1k Views Asked by At

I get this error message while trying to use google vision API

Fatal error: Uncaught Error: Class 'Google\Cloud\Vision\VisionClient' not found in C:\xampp\htdocs\index.php:7 Stack trace: #0 {main} thrown in C:\xampp\htdocs\index.php on line 7

I'm using xampp on windows. I installed Google api using composer (as admin)

composer require google/cloud-vision

I also run (as admin)

composer install
composer update

google cloud sdk is installed.

this is my code

<?php
require 'C:\Users\MyUser\vendor\autoload.php';
use Google\Cloud\Vision\VisionClient;

$path = 'caption.jpg';

$vision = new VisionClient([
    'projectId' => 'my-project-numbers',
    'keyFilePath' => 'my-key.json'
]);

// Annotate an image, detecting faces.
$image = $vision->image(
    fopen($path, 'r'),
    ['text']
);

$tadaa = $vision->annotate($image);

echo '<pre>';
var_dump($tadaa->text());
echo '</pre>';

?>
3

There are 3 best solutions below

1
On

According to the official documentation, I would recommend to use this php client library:

# imports the Google Cloud client library
use Google\Cloud\Vision\V1\ImageAnnotatorClient;

Quickstart: Using client libraries Vision Api

0
On

Using code from https://cloud.google.com/vision/docs/ocr

the following is index.php

<?php
namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ImageAnnotatorClient;

$path = 'caption.jpg';

    $imageAnnotator = new ImageAnnotatorClient();

    # annotate the image
    $image = file_get_contents($path);
    $response = $imageAnnotator->textDetection($image);
    $texts = $response->getTextAnnotations();

    printf('%d texts found:' . PHP_EOL, count($texts));
    foreach ($texts as $text) {
        print($text->getDescription() . PHP_EOL);

        # get bounds
        $vertices = $text->getBoundingPoly()->getVertices();
        $bounds = [];
        foreach ($vertices as $vertex) {
            $bounds[] = sprintf('(%d,%d)', $vertex->getX(), $vertex->getY());
        }
        print('Bounds: ' . join(', ', $bounds) . PHP_EOL);
    }

    $imageAnnotator->close();

?>

I still get

Fatal error: Uncaught Error: Class 'Google\Cloud\Vision\V1\ImageAnnotatorClient' not found in C:\xampp\htdocs\index.php:8 Stack trace: #0 {main} thrown in C:\xampp\htdocs\index.php on line 8

this is composer.json

{
    "require": {
        "google/cloud-vision": "^1.2"
    }
}
0
On

In somes cases, the problem seems related to permissions. In a development server I had the same problem reported from @thepepp, but I could fix it changing the permissions on the vendor folder.

chmod 775 * -R