可以使用composer引用,也可以如下方式引用,将composer的Image类,拷贝到/thinkphp/library/think/image中,

   public function save($pathname, $type = null)
    {
        //自动获取图像类型
        if (is_null($type)) {
            $type = $this->info['type'];
        } else {
            $type = strtolower($type);
        }
        //JPEG图像设置隔行扫描
        if ('jpeg' == $type || 'jpg' == $type) {
            $type = 'jpeg';
            imageinterlace($this->im, 1);
        }
        //保存图像
        if ('gif' == $type && !empty($this->gif)) {
            $this->gif->save($pathname);
        } else {
            $fun = "image{$type}";
            if($type =='png'){
                $fun($this->im, $pathname,5);
            }else{
                $fun($this->im, $pathname,75);
            }
 
        }
 
        return $this;
    }

如果图片大于500,则对非gif格式的图片进行缩略处理

    public function upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info) {
                $fileName = '/uploads/' . $info->getSaveName();
                $fileName = str_replace('\\', '/', $fileName);
                /***压缩图片处理开始***/
                $imgPath = ROOT_PATH ."public".$fileName;
                // 图像大小   图像高度
                list($width, $height, $type, $attr) = @getimagesize($imgPath);
                $fileSize = filesize($imgPath);
                $image = Image::open($imgPath);
                if ($width > 500 && $type != 1) {  //gif图片不能压缩
                    // 如果尺寸大于500 则
                    $image->thumb(450,450,Image::THUMB_SCALING)->save($imgPath);
                }
                /***压缩图片处理结束***/
                $previewPath = $this->request->domain() . $fileName;
                $this->success('上传图片信息', array('path' => $fileName, 'preview_path' => $previewPath));
            } else {
                // 上传失败获取错误信息
                $this->error('上传图片出错', array('path' => $file->getError()));
            }
        }
    }

发表评论

邮箱地址不会被公开。 必填项已用*标注