Search code examples
phplaravelgoogle-cloud-vision

Google Cloud Vision save imagen after detect objects


I am trying to save a image in my database after detect objects with Google cloud vision. I am using php, framework laravel, this is my code,

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();
    }

Could you help me? Thanks


Solution

  • I'm going to assume that you want to grab the raw binary generated by imagejpeg() after processing?

    The only way i know how to do that is using output buffers.

    instead of:

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

    Do:

    <?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();
    

    If you also want to output the image to the browser, return $imgData from your detect_object() function and echo it to the browser

    <?php
    
    $imgData = detect_object($imagen);
    
    header('Content-Type: image/jpeg');
    echo $imgData