Search code examples
phpimagebase64amazon-rekognition

Converting image URL to base64


I am trying to convert an image URL to base 64 (the image itself) to be used in AWS FacialRekognition but there is some error in the code where it doesnt progress past the point of where indexFaces was used as the error log made it here is never printed.

can someone please tell me what i am doing wrong?

    $url= "https://www.thesprucepets.com/thmb/KYaXBSM013GnZ2jEZJnX4a9oIsU=/3865x2174/smart/filters:no_upscale()/horse-galloping-in-grass-688899769-587673275f9b584db3a44cdf.jpg";
    $type = pathinfo($url, PATHINFO_EXTENSION);
    $data = file_get_contents($url);
    $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
            $result = $client->indexFaces([
                'CollectionId' => $id . "blablabla",
                'DetectionAttributes' => ['DEFAULT'],
                'MaxFaces' => 1,
                'QualityFilter' => "NONE",
                'Image' => [ // REQUIRED
                        'Bytes' => $base64
                ]
            ]);
     error_log("MADE IT HERE");

Solution

  • As specified in the Amazon Rekognition documentation, if you're using the AWS PHP SDK, you don't need to base64 the content. You just need to pass the result of file_get_contents.

    So your code would be simpler:

    $url= "https://www.thesprucepets.com/thmb/KYaXBSM013GnZ2jEZJnX4a9oIsU=/3865x2174/smart/filters:no_upscale()/horse-galloping-in-grass-688899769-587673275f9b584db3a44cdf.jpg";
        $result = $client->indexFaces([
                    'CollectionId' => $id . "blablabla",
                    'DetectionAttributes' => ['DEFAULT'],
                    'MaxFaces' => 1,
                    'QualityFilter' => "NONE",
                    'Image' => [ // REQUIRED
                            'Bytes' => file_get_contents($url);
                    ]
         ]);
         error_log("MADE IT HERE");
    

    If you still get an error, it could not be related to the Base64 encoding. Please surround your code with Try/Catch and post the exception