Base64图片的保存

2018-05-23 12:11 By "Powerless" 3150 0 1

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;
        }
    }
}


评 论

View in WeChat

Others Discussion

  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • Mysql联合索引的最左前缀匹配原则
    Posted on 2018-08-25 15:00
  • 2016年云计算热词
    Posted on 2019-06-12 17:53
  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • 巧用CAS解决数据一致性问题
    Posted on 2019-03-07 11:55
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • 通过信鸽来解释HTTPS
    Posted on 2018-10-22 13:56
  • HTTP和HTTPS的区别
    Posted on 2020-08-10 23:00