我想將圖像從它的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