我们在传输和处理图片时,Base64 是一个常用的选择,PHP 中就有函数(base64_encode 和 base64_decode)分别负责图片 Base64 编码和图片 Base64 解码,老王昨天在网上找到 2 段关于图片 Base64 编码和解码的 PHP 代码实现,用起来还不错,这里与大家做个分享。
一、PHP 实现图片 Base64 编码
实现思路主要就是先将图片流读取到 -> 使用 base64_encode() 进行进行编码 -> 拼接上前缀(data:image/png;base64,)
- /**
 - * 图片base64编码
 - * @param string $img
 - * @param bool $imgHtmlCode
 - * author 江南极客
 - * @return string
 - */
 - function imgBase64Encode($img = '', $imgHtmlCode = true)
 - {
 - //如果是本地文件
 - if(strpos($img,'http') === false && !file_exists($img)){
 - return $img;
 - }
 - //获取文件内容
 - $file_content = file_get_contents($img);
 - if($file_content === false){
 - return $img;
 - }
 - $imageInfo = getimagesize($img);
 - $prefiex = '';
 - if($imgHtmlCode){
 - $prefiex = 'data:' . $imageInfo['mime'] . ';base64,';
 - }
 - $base64 = $prefiex.chunk_split(base64_encode($file_content));
 - return $base64;
 - }
 
二、PHP 实现图片 Base64 解码
相比于编码来说,解码稍微复杂一点,因为在对图片进行 Base64 编码的时候会加入前缀字符串(data:image/png;base64,) ,解码之前需要先去掉这一串字符,PHP 代码实现如下:
- /**
 - * 片base64解码
 - * @param string $base64_image_content 图片文件流
 - * @param bool $save_img 是否保存图片
 - * @param string $path 文件保存路径
 - * author 江南极客
 - * @return bool|string
 - */
 - function imgBase64Decode($base64_image_content = '',$save_img = false,$path=''){
 - if(empty($base64_image_content)){
 - return false;
 - }
 - //匹配出图片的信息
 - $match = preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result);
 - if(!$match){
 - return false;
 - }
 - //解码图片内容(方法一)
 - /*$base64_image = preg_split("/(,|;)/",$base64_image_content);
 - $file_content = base64_decode($base64_image[2]);
 - $file_type = substr(strrchr($base64_image[0],'/'),1);*/
 - //解码图片内容(方法二)
 - $base64_image = str_replace($result[1], '', $base64_image_content);
 - $file_content = base64_decode($base64_image);
 - $file_type = $result[2];
 - //如果不保存文件,直接返回图片内容
 - if(!$save_img){
 - return $file_content;
 - }
 - //如果没指定目录,则保存在当前目录下
 - if(empty($path)){
 - $path = __DIR__;
 - }
 - $file_path = $path."/".date('Ymd',time())."/";
 - if(!is_dir($file_path)){
 - //检查是否有该文件夹,如果没有就创建
 - mkdir($file_path,0777,true);
 - }
 - $file_name = time().".{$file_type}";
 - $new_file = $file_path.$file_name;
 - if(file_exists($new_file)){
 - //有同名文件删除
 - @unlink($new_file);
 - }
 - if (file_put_contents($new_file, $file_content)){
 - return $new_file;
 - }
 - return false;
 - }
 
三、在使用 Base64 编码时需要注意的问题
老王昨天在写好服务器端代码后,用在线图片转 Base64 编码工具将一张图片装成了 Base64 编码,再使用在线 Post 进行测试服务器代码时,发现服务器解码得到的图片都是已损坏,无法打开的。后来发现是因为在使用 ajax 传 Base64 编码时,因为 Base64 字符串中有特殊字符,会被转义,所以传到服务器的字符串跟实际的字符串其实不一样,这就导致了 Base64 解码的图片无法打开的问题,后来老王用 Python 写了段测试脚本就没有这个问题了。
如果你也遇到了这个问题,那么老王分享几个网站的解决方案:
1、使用 str.replace(/\&/g,"%26");str.replace(/\+/g,"%2B"); 把字符串中的‘&’、+ 转义
2 、把 base64 图片字符串通过 encodeURIComponent(dataurl) 加密
3、数据格式可以用对象形式传送
