首页 > 解决方案 > 谷歌云视觉在检测到物体后保存图像

问题描述

在使用谷歌云视觉检测对象后,我试图将图像保存在我的数据库中。我正在使用 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();
    }

你可以帮帮我吗?谢谢

标签: phplaravelgoogle-cloud-vision

解决方案


我将假设您想获取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();

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

<?php

$imgData = detect_object($imagen);

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

推荐阅读