Base64图片的保存

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

  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15
  • BASE原则
    Posted on 2020-12-17 16:42
  • 程序员年中考试题-段子版
    Posted on 2021-06-23 15:57