Base64图片的保存

2018-05-23 12:11 By "Powerless" 3120 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 2021-04-09 16:52
  • Redis各种数据类型的使用场景举例分析【二】
    Posted on 2018-11-22 10:30
  • QPS、TPS、RT、吞吐量到底是什么
    Posted on 2020-02-02 01:15
  • 2018年云计算热词
    Posted on 2019-06-12 18:19
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • ACID原则
    Posted on 2020-12-17 16:36
  • 前端知识体系精简-Css
    Posted on 2018-03-28 18:34
  • 浏览器访问网站经历的步骤-Html
    Posted on 2018-11-28 18:48