fastadmin upload上传图片压缩

只需要将这段代码放在中间

php 复制代码
// ++++++++++++++++++++++++++++++++++++++++++++++++++++
// 【图片压缩处理】开始
// ++++++++++++++++++++++++++++++++++++++++++++++++++++
            //            dump($destDir);
//            dump($fileName);
//            exit;
            $mime = $this->file->getMime();
            $filePath = $this->file->getPathname();
            $maxSize = 1024 * 1024; // 超过1MB才压缩(可选)
            $quality = 30;         // 压缩质量 1-100
//            dump($filePath);
//            dump($mime);
//            exit;
// 只压缩图片
            if (in_array($mime, ['image/jpeg', 'image/png', 'image/gif', 'image/webp'])) {
                // 获取图像尺寸
                $imgInfo = getimagesize($filePath);
//                dump($imgInfo);
                if ($imgInfo) {
                    list($width, $height) = $imgInfo;
                    $maxWidth = 1920;  // 最大宽度
                    $maxHeight = 1920; // 最大高度

                    // 等比缩放
                    $ratio = min($maxWidth / $width, $maxHeight / $height);
                    if ($ratio < 1) {
                        $newWidth = (int)($width * $ratio);
                        $newHeight = (int)($height * $ratio);
                    } else {
                        $newWidth = $width;
                        $newHeight = $height;
                    }

                    // 创建画布
                    $image = imagecreatefromstring(file_get_contents($filePath));
                    $newImage = imagecreatetruecolor($newWidth, $newHeight);

                    // PNG透明处理
                    if ($mime == 'image/png') {
                        imagealphablending($newImage, false);
                        imagesavealpha($newImage, true);
                    }

                    // 复制缩放
                    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

                    // 覆盖原文件(压缩后替换)
                    switch ($mime) {
                        case 'image/jpeg':
                            imagejpeg($newImage, $filePath, $quality);
                            break;
                        case 'image/png':
                            imagepng($newImage, $filePath, (int)($quality / 10));
                            break;
                        case 'image/gif':
                            imagegif($newImage, $filePath);
                            break;
                        case 'image/webp':
                            imagewebp($newImage, $filePath, $quality);
                            break;
                    }

                    // 销毁资源
                    imagedestroy($image);
                    imagedestroy($newImage);
                }
            }

// ++++++++++++++++++++++++++++++++++++++++++++++++++++
// 【图片压缩处理】结束
// ++++++++++++++++++++++++++++++++++++++++++++++++++++
php 复制代码
/**
     * 普通上传
     * @return \app\common\model\attachment|\think\Model
     * @throws UploadException
     */
    public function upload($savekey = null)
    {
        if (empty($this->file)) {
            throw new UploadException(__('No file upload or server upload limit exceeded'));
        }

        $this->checkSize();
        $this->checkExecutable();
        $this->checkMimetype();
        $this->checkImage();

        $savekey = $savekey ? $savekey : $this->getSavekey();
        $savekey = '/' . ltrim($savekey, '/');
        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);

        $destDir = ROOT_PATH . 'public' . str_replace('/', DS, $uploadDir);

        $sha1 = $this->file->hash();

        //如果是合并文件
        if ($this->merging) {
            if (!$this->file->check()) {
                throw new UploadException($this->file->getError());
            }
            $destFile = $destDir . $fileName;
            $sourceFile = $this->file->getRealPath() ?: $this->file->getPathname();
            $info = $this->file->getInfo();
            $this->file = null;
            if (!is_dir($destDir)) {
                @mkdir($destDir, 0755, true);
            }
            rename($sourceFile, $destFile);
            $file = new File($destFile);
            $file->setSaveName($fileName)->setUploadInfo($info);
        } else {
// ++++++++++++++++++++++++++++++++++++++++++++++++++++
// 【图片压缩处理】开始
// ++++++++++++++++++++++++++++++++++++++++++++++++++++
            //            dump($destDir);
//            dump($fileName);
//            exit;
            $mime = $this->file->getMime();
            $filePath = $this->file->getPathname();
            $maxSize = 1024 * 1024; // 超过1MB才压缩(可选)
            $quality = 30;         // 压缩质量 1-100
//            dump($filePath);
//            dump($mime);
//            exit;
// 只压缩图片
            if (in_array($mime, ['image/jpeg', 'image/png', 'image/gif', 'image/webp'])) {
                // 获取图像尺寸
                $imgInfo = getimagesize($filePath);
//                dump($imgInfo);
                if ($imgInfo) {
                    list($width, $height) = $imgInfo;
                    $maxWidth = 1920;  // 最大宽度
                    $maxHeight = 1920; // 最大高度

                    // 等比缩放
                    $ratio = min($maxWidth / $width, $maxHeight / $height);
                    if ($ratio < 1) {
                        $newWidth = (int)($width * $ratio);
                        $newHeight = (int)($height * $ratio);
                    } else {
                        $newWidth = $width;
                        $newHeight = $height;
                    }

                    // 创建画布
                    $image = imagecreatefromstring(file_get_contents($filePath));
                    $newImage = imagecreatetruecolor($newWidth, $newHeight);

                    // PNG透明处理
                    if ($mime == 'image/png') {
                        imagealphablending($newImage, false);
                        imagesavealpha($newImage, true);
                    }

                    // 复制缩放
                    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

                    // 覆盖原文件(压缩后替换)
                    switch ($mime) {
                        case 'image/jpeg':
                            imagejpeg($newImage, $filePath, $quality);
                            break;
                        case 'image/png':
                            imagepng($newImage, $filePath, (int)($quality / 10));
                            break;
                        case 'image/gif':
                            imagegif($newImage, $filePath);
                            break;
                        case 'image/webp':
                            imagewebp($newImage, $filePath, $quality);
                            break;
                    }

                    // 销毁资源
                    imagedestroy($image);
                    imagedestroy($newImage);
                }
            }

// ++++++++++++++++++++++++++++++++++++++++++++++++++++
// 【图片压缩处理】结束
// ++++++++++++++++++++++++++++++++++++++++++++++++++++
            $file = $this->file->move($destDir, $fileName);
            if (!$file) {
                // 上传失败获取错误信息
                throw new UploadException($this->file->getError());
            }
        }
        $this->file = $file;
        $category = request()->post('category');
        $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
        $auth = Auth::instance();
        $params = array(
            'admin_id'    => (int)session('admin.id'),
            'user_id'     => (int)$auth->id,
            'filename'    => mb_substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100),
            'category'    => $category,
            'filesize'    => $this->fileInfo['size'],
            'imagewidth'  => $this->fileInfo['imagewidth'],
            'imageheight' => $this->fileInfo['imageheight'],
            'imagetype'   => $this->fileInfo['suffix'],
            'imageframes' => 0,
            'mimetype'    => $this->fileInfo['type'],
            'url'         => $uploadDir . $file->getSaveName(),
            'uploadtime'  => time(),
            'storage'     => 'local',
            'sha1'        => $sha1,
            'extparam'    => '',
        );
        $attachment = new Attachment();
        $attachment->data(array_filter($params));
        $attachment->save();

        \think\Hook::listen("upload_after", $attachment);
        return $attachment;
    }
相关推荐
五岁小孩3 天前
免费图片压缩工具哪个最好用?实测 5 款免登录无损压缩网站
图片压缩·压缩图片·压缩图片工具·在线免费图片压缩
yuananyun8 天前
网站性能优化:如何批量将图片转换为 WebP 和 AVIF 格式?
图片压缩·图片格式转换·小算云箱
JSON_L12 天前
FastAdmin 短信插件开发完整教程
php·fastadmin
vivo互联网技术15 天前
下一代图片格式 AVIF 在 vivo 社区的落地实践
前端·性能优化·图片压缩·avif
JSON_L1 个月前
PHP 使用天地图
php·fastadmin
Sheldon一蓑烟雨任平生1 个月前
Vite 深度剖析(四)
性能优化·vite·图片压缩·gzip压缩·代码压缩·摇树·dns-prefetch
appleคิดถึง1 个月前
fastadmin后台配置腾讯云cos插件后,解决自定义后台的上传问题
云计算·腾讯云·cos·fastadmin
JSON_L1 个月前
Fastadmin中实现敏感词管理
数据库·php·fastadmin
JSON_L1 个月前
Fastadmin控制台增加用户活跃统计
php·fastadmin