2010-12-03 81 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,即使文件讀取成功。實際上在這種情況下,它不應該發生,但是在獲取文件內容時這是一個很好的做法。