您现在的位置是:网站首页>PHP技术PHP技术
处理base64格式图片,存储并返回文件名
草谷2019-03-30【PHP技术】
简介用法比较简单,直接将base64的代码传入,即可返回创建后的文件名
/**
* 将base64图片转换存储并返回路径
* @param $base64_img string base64格式的文件
* @param $is_path bool 默认返回相对路径,为真则返回绝对路径
* @return mixed|string 文件路径
*/
function base64_to_img($base64_img, $is_path = false)
{
//校验是不是真实base64
$check = substr($base64_img, 0, 10);
if ($check != 'data:image') {
return '';
}
$up_dir = '.' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . date('Ymd', time()) . DIRECTORY_SEPARATOR; //存放目录
if (!file_exists($up_dir)) {
mkdir($up_dir, 0777);
}
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
$type = $result[2];
// dump($base64_img);
// dump($type);
// dump($result);
// exit;
if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
$new_file = $up_dir . date('YmdHis_') . rand(10000, 99999) . '.' . $type;
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))) {
$img_path = str_replace('../../..', '', $new_file);
$img_path = substr($img_path, 16, strlen($img_path) - 1);
if ($is_path) {
//返回绝对路径
return 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/images' . $img_path;
} else {
//返回相对路径
return $img_path;
}
} else {
return '';
}
} else {
//文件类型错误
return '';
}
} else {
//文件错误
return '';
}
}很赞哦! (3)
上一篇: php判断身份证号码正则校验
下一篇: PHP将银行卡号处理为每4位一个空格
相关文章
文章评论
点击排行
TP5入口文件被修改的问题处理