3 回答

TA貢獻1795條經(jīng)驗 獲得超7個贊
當您編碼為 base64 時,svg 和 (jpg-png-jpeg) 之間存在差異。當您處理 png 圖像時,您基本上可以使用 png 擴展名。但是你基本上不能使用svg。使用 svg 時需要 svg+xml。
function img_enc_base64 ($filepath){ // img_enc_base64() is manual function you can change the name what you want.
if (file_exists($filepath)){
$filetype = pathinfo($filepath, PATHINFO_EXTENSION);
if ($filetype==='svg'){
$filetype .= '+xml';
}
$get_img = file_get_contents($filepath);
return 'data:image/' . $filetype . ';base64,' . base64_encode($get_img );
}
}
所以現(xiàn)在
echo img_enc_base64('file_path'); // is your base64 code of image
<img src="<?php echo img_enc_base64('file_path');?>" alt=""> // is your image
文件路徑示例:pics/my_book.png

TA貢獻1827條經(jīng)驗 獲得超9個贊
我不友好,Laraval但我有一個經(jīng)過測試的答案寫在PHP
<?php
? ? $path = "files/user_avatar.png";
? ? $type = pathinfo($path, PATHINFO_EXTENSION);
? ? $data = file_get_contents($path);
? ? $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
? ? # print to make sure that it is working or not
? ? echo $base64."<br>";
? ? # Or, show it as a clean image
? ? echo '<img scr="'.$base64.'" height="150" width="150">';
?>
上面的代碼片段僅僅因為功能而不起作用file_get_contents
。
解決方案:
使用curl_get_contents()
而不是file_get_contents
curl_get_contents()
function curl_get_contents($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
file_get_contents替換成后curl_get_contents
$path = "files/user_avatar.png";
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = curl_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
# print to make sure that it is working or not
echo $base64."<br>";
# Or, show it as a clean image
echo '<img scr="'.$base64.'" height="150" width="150">';
加載時間仍然太長? 嘗試檢查您的文件大小或嘗試檢查Server-Configuration
希望對你有幫助??

TA貢獻1943條經(jīng)驗 獲得超7個贊
我認為應該是:
$path = 'files/user_avatar.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
請記住,這會將數(shù)據(jù)擴大 33%,并且文件大小超過內(nèi)存限制時會出現(xiàn)問題。
- 3 回答
- 0 關(guān)注
- 193 瀏覽
添加回答
舉報