如何将图像从URL转换为Base64编码?


当前回答

以防你(出于某种原因)无法使用curl或file_get_contents,你可以使用以下方法:

$img = imagecreatefrompng('...');
ob_start();
imagepng($img);
$bin = ob_get_clean();
$b64 = base64_encode($bin);

其他回答

容易:

$imagedata = file_get_contents("/path/to/image.jpg");
             // alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);

请记住,这将使数据扩大33%, 如果文件的大小超过了memory_limit,就会出现问题。

下面是一个使用cURL调用的例子…这比file_get_contents()函数更好。当然,使用base64_encode()。

<?php
    $url = "http://example.com";

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
?>

<img src="data:image/png;base64,<?php echo base64_encode($output);?>">
<img src="data:image/png;base64,<?php echo base64_encode(file_get_contents("IMAGE URL HERE")) ?>">

我试图使用这个资源,但我一直得到一个错误。我发现上面的代码工作得很完美。

我只是将“IMAGE URL HERE”替换为您的图像的URL - http://www.website.com/image.jpg

我认为应该是:

$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

下面是上传代码,用于编码并保存到MySQL数据库:

if (!isset($_GET["getfile"])) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Error: " . $_FILES["file"]["error"] . "<br>";
    } else {
        move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);

        $bin_string = file_get_contents($_FILES["file"]["name"]);
        $hex_string = base64_encode($bin_string);
        $mysqli = mysqli_init();

        if (!$mysqli->real_connect('localhost', 'root', '', 'arihant')) {
            die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
        }

        $mysqli->query("INSERT INTO upload(image) VALUES ('" . $hex_string . "')");
    }
}

为了显示图像,使用这个:

echo "<img src='data:image/jpeg;base64, $image' width=300>";