Base64图片的保存

2018-05-23 12:11 By "Powerless" 3111 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 2018-11-28 19:10
  • HTTP头中隐藏PHP版本号
    Posted on 2021-01-11 16:38
  • MySQL中的行级锁,表级锁,页级锁
    Posted on 2018-08-25 11:00
  • QPS、TPS、RT、吞吐量到底是什么
    Posted on 2020-02-02 01:15
  • MySQL事务介绍
    Posted on 2019-06-05 18:14
  • 能创建多少个 TCP 连接?
    Posted on 2021-08-02 16:00
  • PHP 基金会来啦!
    Posted on 2022-10-08 17:40
  • 2018年云计算热词
    Posted on 2019-06-12 18:19