Google Cloud Vision 在检测到物体后保存图像

Google Cloud Vision save imagen after detect objects

我试图在使用 Google 云视觉检测到物体后将图像保存在我的数据库中。我正在使用 php,框架 laravel,这是我的代码,

function detect_object($imagen){
        $path = $imagen->getRealPath();
        $imageAnnotator = new ImageAnnotatorClient(['credentials' => base_path('credentials.json')]);

        $output = imagecreatefromjpeg($path);
        list($width, $height, $type, $attr) = getimagesize($path);

        # annotate the image
        $image = file_get_contents($path);
        $response = $imageAnnotator->objectLocalization($image);
        $objects = $response->getLocalizedObjectAnnotations();

        foreach ($objects as $object) {
            $name = $object->getName();
            $score = $object->getScore();
            $vertices = $object->getBoundingPoly()->getNormalizedVertices();
            // printf('%s (confidence %f)):' . PHP_EOL, $name, $score);
            // print('normalized bounding polygon vertices: ');
            // foreach ($vertices as $vertex) {
            //     printf(' (%f, %f)', $vertex->getX(), $vertex->getY());
            // }
            // print(PHP_EOL);
            $vertices_finales = [];
            foreach ($vertices as $vertex) {
                array_push($vertices_finales, ($vertex->getX() * $width));
                array_push($vertices_finales, ($vertex->getY() * $height));
            }
            imagepolygon($output, $vertices_finales, (sizeof($vertices_finales) / 2), 0x00ff00);
            imagestring($output, 5, ($vertices_finales[0] + 10), ($vertices_finales[1] + 10), $name, 0x00ff00);
        }

        header('Content-Type: image/jpeg');
        imagejpeg($output);
        imagedestroy($output);
        $imageAnnotator->close();
    }

你能帮帮我吗? 谢谢

我假设您想在处理后获取 imagejpeg() 生成的原始二进制文件?

我知道如何做到这一点的唯一方法是使用输出缓冲区。

而不是:

<?php

header('Content-Type: image/jpeg');
imagejpeg($output);
imagedestroy($output);
$imageAnnotator->close();

做:

<?php

ob_start();
imagejpeg($output);
$imgData = ob_get_clean();
# Do what you want with imgData, like insert into a binary field in a db, write to disk, etc

imagedestroy($output);
$imageAnnotator->close();

如果您还想将图像输出到浏览器,return $imgData 从您的 detect_object() 函数并将其回显到浏览器

<?php

$imgData = detect_object($imagen);

header('Content-Type: image/jpeg');
echo $imgData