Search code examples
phpamazon-web-servicesamazon-rekognition

AWS Rekognition PHP SDK gives invalid image encoding error


I am using the PHP SDK to upload a local file (not S3) to be parsed in AWS Rekognition. However, the image blob will not work and I get the message: InvalidImageFormatException: "Invalid image encoding".

I've tried multiple images (the docs say JPEGs and PNGs are accepted), but none work.

My code is:

$client = new RekognitionClient($credentials);

$im = file_get_contents('/app/image1.png');
$imdata = base64_encode($im);

$result = $client->detectLabels(
    [
       'Image' => [
          'Bytes' => $imdata,
       ]
    ]
);

Am I encoding it correctly? The docs are quite vague.

I've found SO questions about 'No Image Content', but none about invalid format.

Any ideas? Thanks!


Solution

  • I ended up using Imagick rather than the base64_encode route. I suspect this isn't the best way, but it does work great!

    $client = new RekognitionClient($credentials);
    
    $image = new Imagick('/app/image1.png');
    $imdata = $image->getImageBlob();
    
    $result = $client->detectLabels(
        [
           'Image' => [
              'Bytes' => $imdata,
           ]
        ]
    );