我想将图像从它的url转换为base64。PHP:如何将图像从URL转换为Base64?
10
A
回答
23
是否要创建数据网址?您需要MIME类型和其他一些附加信息(请参阅Wikipedia)。如果不是这种情况,这将是图像的简单的Base64表示:
$b64image = base64_encode(file_get_contents('path/to/image.png'));
相关的文档:base64_encode()
-function,file_get_contents()
-function。
1
2
我不知道,但检查这个例子http://www.php.net/manual/es/function.base64-encode.php#99842
商祺!
8
试试这个: -
例一: -
<?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'); ?>"/>
例二: -
$path= 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
4
我对这个问题寻找一个类似的解决方案,其实,我理解这是原始问题。
我想这样做,但该文件是在一个远程服务器上,所以这是我做过什么:
$url = 'http://yoursite.com/image.jpg';
$image = file_get_contents($url);
if ($image !== false){
return 'data:image/jpg;base64,'.base64_encode($image);
}
所以,这个代码是返回字符串的函数,你可以在html中输出img标签的src参数内的返回值。我使用smarty作为我的模板库。这可能是这样的:
<img src="<string_returned_by_function>">
注意的显式调用:
if ($image !== false)
这是必要的,因为的file_get_contents可以返回0,并在某些情况下,被铸造为false,即使文件读取成功。实际上在这种情况下,它不应该发生,但是在获取文件内容时这是一个很好的做法。
你的例子2正是我正在寻找的。为此+1。 – 2014-10-23 09:56:45