PHP:如何将图像从URL转换为Base64?

Sha*_*arj 18 php binary base64

我想将图像从其URL转换为base64.

jwu*_*ler 39

你想创建一个数据网址吗?您需要MIME类型和其他一些其他信息(参见维基百科).如果不是这种情况,这将是图像的简单base64表示:

$b64image = base64_encode(file_get_contents('path/to/image.png'));
Run Code Online (Sandbox Code Playgroud)

相关文档:base64_encode()-function,file_get_contents()-function.


mce*_*ron 12

我得到了这个问题,寻找类似的解决方案,实际上,我明白这是最初的问题.

我想做同样的事,但文件是在远程服务器上,所以这就是我做的:

$url = 'http://yoursite.com/image.jpg';
$image = file_get_contents($url);
if ($image !== false){
    return 'data:image/jpg;base64,'.base64_encode($image);

}
Run Code Online (Sandbox Code Playgroud)

因此,此代码来自返回字符串的函数,您可以在html中的img标记的src参数内输出返回值.我使用smarty作为我的模板库.它可能是这样的:

<img src="<string_returned_by_function>">
Run Code Online (Sandbox Code Playgroud)

请注意显式调用:

if ($image !== false)
Run Code Online (Sandbox Code Playgroud)

这是必要的,因为即使文件获取成功,file_get_contents也可以返回0并在某些情况下被转换为false.实际上在这种情况下它不应该发生,但它在获取文件内容时是一个很好的做法.


Gau*_*g P 9

试试这个:-

例一: -

<?php 
function base64_encode_image ($filename=string,$filetype=string) {
    if ($filename) {
        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
        return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
    }
}
?>

used as so

<style type="text/css">
.logo {
    background: url("<?php echo base64_encode_image ('img/logo.png','png'); ?>") no-repeat right 5px;
}
</style>

or

<img src="<?php echo base64_encode_image ('img/logo.png','png'); ?>"/>
Run Code Online (Sandbox Code Playgroud)

例二: -

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