PHP保存Base64图片base64_decode的问题整理

yipeiwu_com6年前PHP代码库

PHP对Base64的支持非常好,有内置的base64_encode与base64_decode负责图片的Base64编码与解码。

编码上,只要将图片流读取到,而后使用base64_encode进行进行编码即可得到。

/**
 * 获取图片的Base64编码(不支持url) *
 * @param $img_file 传入本地图片地址 *
 * @return string
 */
function imgToBase64($img_file) {
  $img_base64 = '';
  if (file_exists($img_file)) {
    $app_img_file = $img_file; // 图片路径
    $img_info = getimagesize($app_img_file); // 取得图片的大小,类型等
    $fp = fopen($app_img_file, "r"); // 图片是否可读权限
    if ($fp) {
      $filesize = filesize($app_img_file);
      $content = fread($fp, $filesize);
      $file_content = chunk_split(base64_encode($content)); // base64编码
      switch ($img_info[2]) {      //判读图片类型
        case 1: $img_type = "gif";
          break;
        case 2: $img_type = "jpg";
          break;
        case 3: $img_type = "png";
          break;
      }
      $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
    }
    fclose($fp);
  }
  return $img_base64; //返回图片的base64
}

//调用使用的方法

$img_dir = dirname(__FILE__) . '/uploads/img/wwllwedd.jpg';
$img_base64 = imgToBase64($img_dir);
echo '<img src="' . $img_base64 . '">'; //图片形式展示
echo '<hr>';
echo $img_base64; //输出Base64编码

而解码就略微麻烦一点,究其原因在于把图片编码成base64字符串后,编码内会加入这些字符 data:image/png;base64,本来是用于base64进行识别的。但是如果直接放到php里用base64_decode函数解码会导致最终保存的图片文件格式损坏,而解决方法就是先去掉这一串字符

//方法一
preg_match('/^(data:\s*image\/(\w+);base64,)/', $base_info, $result) // 可以判断是否是 base64的图片
$type = $result[2];
$extensions = strtolower($type);
if (!in_array($extensions, array('gif', 'jpg', 'png', 'jpeg','bmp'))) {
  json_rtn(0, '上传的图片不在允许内');
}
$data= base64_decode(str_replace($result[1], '', $base_info));  //对截取后的字符使用base64_decode进行解码
file_put_contents($pic_path,$data) //写入文件并保存
 
//方法二
$base64_string= explode(',', $base64_string); //截取data:image/png;base64, 这个逗号后的字符
$data= base64_decode($base64_string[1]);  //对截取后的字符使用base64_decode进行解码
file_put_contents($url, $data); //写入文件并保存

以上就是本次介绍的关于PHP保存Base64图片base64_decode的问题内容,感谢大家的学习和对【宜配屋www.yipeiwu.com】的支持。

相关文章

php数组函数序列之in_array() 查找数组值是否存在

in_array() 定义和用法 in_array() 函数在数组中搜索给定的值。 语法 in_array(value,array,type) 参数 描述 value 必需。规定要在数组...

php输出文字乱码的解决方法

php输出文字乱码的解决办法: 在php文件最开头写上: <?php header('Content-type: text/html; charset=UTF8');...

解析关于wamp启动是80端口被占用的问题

解析关于wamp启动是80端口被占用的问题

问题如下:网上有关于这个处理办法,说道:VS2010在更新了SP1后,会在开机时自动启动一个服务,占用WAMP的80端口,导致WAMP无法正常启动Apache。提示信息:Your por...

PHP面向对象分析设计的61条军规小结

(1)所有数据都应该隐藏在所在的类的内部。 (2)类的使用者必须依赖类的共有接口,但类不能依赖它的使用者。 (3)尽量减少类的协议中的消息。 (4)实现所有类都理解的最基本公有接口[例如...

phpmailer发送gmail邮件实例详解

复制代码 代码如下:<html><head><title>PHPMailer - SMTP (Gmail) basic test</title&...