有时候前端会对图片进行一些裁剪操作,完成后前端会返回给我们一个Base64的图片编码,我们需要去吧这个编码转换成一个图片文件储存,下面我简单的写了一个Base64图片的保存方法。
class Image
{
protected $img_path = 'public/image/';
public function uploadImg($base64_image_content){
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
//图片后缀
$type = $result[2];
//保存位置--图片名
$root = ROOT_PATH.$this->img_path;
$paths = $root.'Default/'.$this->upPath();
$this->checkPath($paths);
$image_name=$this->upName().".".$type;
//解码
$decode=base64_decode(str_replace($result[1], '', $base64_image_content));
if (file_put_contents($paths.$image_name, $decode)){
$data['code']=0;
$data['path'] = $this->upPath();
$data['file'] = $image_name;
$data['msg']='保存成功!';
}else{
$data['code']=400;
$data['error']='图片保存失败!';
}
}else{
$data['code']=400;
$data['error']='base64图片格式有误!';
}
return $data;
}
public function upPath()
{
return date('Y/m/');
}
public function upName()
{
return (microtime (true)*10000);
}
protected function checkPath($path)
{
if (is_dir($path)) {
return true;
}
if (mkdir($path, 0755, true)) {
return true;
} else {
$this->error = "目录 {$path} 创建失败!";
return false;
}
}
}
登录后可发表评论