首页 文章

将POSTed图像转换为Base64

提问于
浏览
-1

我有一个我正在使用的网站,它使用imgur api上传用户的 Profiles 图片,但它需要是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编码 .

谢谢 :)

编辑:这篇文章与标记为重复的帖子不同,因为我想知道如何将表单数据发送到其他地方,而不是将其上传到我的网站 .

1 回答

  • 2

    上传文件的信息包含$ _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);
    

相关问题