PHP保存Base64图片base64_decode的问题整理
发布时间:2020-05-25 06:35:56 所属栏目:PHP 来源:互联网
导读:PHP保存Base64图片base64_decode的问题整理 PHP对Base64的支持非常好,有内置的base64_encode与base64_decode负责图片的Base64编码与解码. 编码上,只要将图片流读取到,而后使用base64_encode进行进行编码即可得到. /** * 获取图片的Base64编码(不支持url) * *
|
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的问题内容,感谢大家的学习和对我们的支持。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
