2010-12-03 80 views

回答

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); 
+0

你的例子2正是我正在寻找的。为此+1。 – 2014-10-23 09:56:45

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,即使文件读取成功。实际上在这种情况下,它不应该发生,但是在获取文件内容时这是一个很好的做法。