php实现 data url的图片生成与保存 原创
DataURL是在本地直接绘制图片,不是从服务器加载,所以节省了HTTP连接,起到加速网页的作用。
语法:
data:image/jpg; 声明数据协议及类型名称
base64, 编码形式为base64
/9j/4AAQSkZ…… base64编码结果
DataURL的生成方法(php):
<?php $img_file=file_get_contents("https://www.nhooo.com/img/logo_s2.png"); echobase64_encode($img_file);
注意:本方法适合于小图片,大图片就不要考虑了,另外IE8以下浏览器不支持这种方法。用这种方法会加重客户端的CPU和内存负担,总之有利有弊。
那么我们如何把网站上的DataURL格式的图片转存成实际图片呢?
其实很简单,我们把图片内容就是src部分传到后台,保存即可。
$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; } }