将图像 URL 转换为 base64

问题描述

我正在尝试将图像 URL 转换为要在 AWS FacialRekognition 中使用的 base 64(图像本身),但代码中有一些错误,它没有超过使用 indexFaces 作为错误日志的点它从不在这里打印。

谁能告诉我我做错了什么?

    $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");

解决方法

Amazon Rekognition documentation, 中所述,如果您使用的是 AWS PHP 开发工具包,则不需要对内容进行 base64。你只需要传递file_get_contents的结果。

所以你的代码会更简单:

$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");

如果仍然出现错误,则可能与 Base64 编码无关。请用 Try/Catch 包围您的代码并发布异常