将发布的图像转换为 Base64

Convert POSTed Image to Base64

我有一个我正在使用的网站,它使用 imgur api 来上传用户的个人资料图片,但它需要是 base64 才能使用我拥有的功能:

function imgur($image) {
    $client_id = "client_id_some_numbers_and_stuff";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
    curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode($image)));
    $reply = curl_exec($ch);
    curl_close($ch);
    $reply = json_decode($reply);
    $link = $reply->data->link;
    return $link;
}

我从表单输入中获取图像 (<input type="file" id="pp" name="pp">)。当我从 $_POST["pp"] 获取数据时,它被设置为文件名的字符串,没有任何用处。

如何获取图像文件并将其传递给 imgur() 函数,或者将其转换为 base64,然后将其传递给 imgur() 函数,然后只需从中删除 base64 编码函数。

谢谢:)

编辑:这个 post 与标记为重复的那个不同,因为我想知道如何将表单数据发送到其他地方,而不是将其上传到我的网站。

上传文件的信息包含 $_FILES 数组

您需要在服务器中获取上传文件路径并将其转换为 base64

$image = $_FILES["pp"]["tmp_name"];
$type = pathinfo($image, PATHINFO_EXTENSION);
$data = file_get_contents($image);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
imgur($base64);