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


当前回答

容易:

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

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

其他回答

非常简单且常用的:

function getDataURI($imagePath) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $type = $finfo->file($imagePath);
    return 'data:' . $type . ';base64,' . base64_encode(file_get_contents($imagePath));
}

// Use the above function like below:
echo '<img src="' . getDataURI('./images/my-file.svg') . '" alt="">';
echo '<img src="' . getDataURI('./images/my-file.png') . '" alt="">';

注意:文件的MIME类型将自动添加(从PHP文档中获得帮助)。

<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

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

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

也可以用这种方式来表示base64编码格式的图像…

找到PHP函数file_get_content,然后使用函数base64_encode。

并获取结果来准备str作为数据:"。file_mime_type。" Base64_encoded string。在img src属性中使用它。下面的代码可能会有帮助:

// A few settings
$img_file = 'raju.jpg';

// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;

// Echo out a sample image
echo '<img src="'.$src.'">';

下面是一个使用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);?>">