Data URL是在本地直接繪制圖片,不是從服務(wù)器加載,所以節(jié)省了HTTP連接,起到加速網(wǎng)頁(yè)的作用。
語法:
data:image/jpg; 聲明數(shù)據(jù)協(xié)議及類型名稱
base64, 編碼形式為base64
/9j/4AAQSkZ…… base64編碼結(jié)果
Data URL的生成方法(php):
<?php $img_file = file_get_contents("http://www.zmynmublwnt.cn/img/logo_s2.png"); echo base64_encode($img_file);
注意:本方法適合于小圖片,大圖片就不要考慮了,另外IE8以下瀏覽器不支持這種方法。用這種方法會(huì)加重客戶端的CPU和內(nèi)存負(fù)擔(dān),總之有利有弊。
那么我們?nèi)绾伟丫W(wǎng)站上的Data URL格式的圖片轉(zhuǎn)存成實(shí)際圖片呢?
其實(shí)很簡(jiǎn)單,我們把圖片內(nèi)容就是src部分傳到后臺(tái),保存即可。
1
2
3
4
5
6
7
8
|
$img_content // 圖片內(nèi)容 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 ; } } |