Data URL是在本地直接繪制圖片,不是從服務器加載,所以節省了HTTP連接,起到加速網頁的作用。
語法:
data:image/jpg; 聲明數據協議及類型名稱
base64, 編碼形式為base64
/9j/4AAQSkZ…… base64編碼結果
Data URL的生成方法(php):
<?php $img_file = file_get_contents("http://m.ythuaji.com.cn/img/logo_s2.png"); echo base64_encode($img_file);
注意:本方法適合于小圖片,大圖片就不要考慮了,另外IE8以下瀏覽器不支持這種方法。用這種方法會加重客戶端的CPU和內存負擔,總之有利有弊。
那么我們如何把網站上的Data URL格式的圖片轉存成實際圖片呢?
其實很簡單,我們把圖片內容就是src部分傳到后臺,保存即可。
1
2
3
4
5
6
7
8
|
$img_content // 圖片內容 if (preg_match( '/^(data:\s*image\/(\w+);base64,)/' , $img_content , $result )){ $type = $result [2]; $new_file = "./test.{$type}" ; if ( file_put_contents ( $new_file , base64_decode ( str_replace ( $result [1], '' , $img_content )))){ echo '新文件保存成功:' , $new_file ; } } |