Base64图片的保存

2018-05-23 12:11 By "Powerless" 3006 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;
        }
    }
}


评 论

Others Discussion

  • 分布式服务限流
    Posted on 2020-02-07 18:57
  • 有状态服务VS无状态服务
    Posted on 2020-02-07 18:18
  • 企业级PAAS云平台几个关键问题和挑战
    Posted on 2019-06-12 18:33
  • MySQL 单库后期分库策略
    Posted on 2019-08-19 14:31
  • Redis七大经典问题
    Posted on 2021-05-27 11:14
  • 关于HTTPS的五大误区
    Posted on 2020-02-02 01:10
  • PHP实现精确发布时间
    Posted on 2018-12-06 21:00
  • 为什么要测量尾部延迟
    Posted on 2020-09-18 10:34