博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

PHP 图片base64 互转

Posted on 2017-01-19 09:44  PHP-张工  阅读(512)  评论(0编辑  收藏  举报
<?php

/*
http://tool.css-js.com/base64.html
透明图片
<img src="data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAABpJREFUeNpi/P//PwMxgImBSDCqkDoKAQIMANUSAxFqvpFcAAAAAElFTkSuQmCC">
白色图片
<img src="data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAABhJREFUeNpi/P//PwNuwMSAF4xUaYAAAwCl4wMRhhRWpQAAAABJRU5ErkJggg==">
红色图片
<img src="data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAABVJREFUeNpi/M+ADzAxjEpjAQABBgBBLAETbs/ntQAAAABJRU5ErkJggg==">
*/

// base64 转图片
$base64 = "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAABVJREFUeNpi/M+ADzAxjEpjAQABBgBBLAETbs/ntQAAAABJRU5ErkJggg==";
$img = base64_decode($base64);
file_put_contents(__DIR__ . '/null.jpg', $img);//返回的是字节数


// 图片转 base64
$a = file_get_contents(__DIR__ . '/null.png');
echo '<img src="data:image/jpg;base64,' . base64_encode($a) . '">';

/*
在HTML使用base64编码, 叫做Data URI scheme. 

Data URI scheme目前支持的类型有:

data:,文本字串
data:text/plain,%s
data:text/html,%s
data:text/html;base64,%s
data:text/css,%s
data:text/css;base64,%s
data:text/javascript,%s
data:text/javascript;base64,%s
data:image/gif;base64,%s
data:image/png;base64,%s
data:image/jpeg;base64,%s
data:image/x-icon;base64,%s
*/