欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > php >内容正文

php

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

发布时间:2025/4/16 php 62 豆豆
生活随笔 收集整理的这篇文章主要介绍了 php base64_decode 图片,PHP保存Base64图片base64_decode的问题整理 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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 ''; //图片形式展示

echo '


';

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的问题内容,感谢大家的学习和对脚本之家的支持。

总结

以上是生活随笔为你收集整理的php base64_decode 图片,PHP保存Base64图片base64_decode的问题整理的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。