Explorar o código

图片压缩调用

moonsflyer hai 4 meses
pai
achega
d5deab660f
Modificáronse 1 ficheiros con 38 adicións e 0 borrados
  1. 38 0
      app/common/service/storage/engine/Server.php

+ 38 - 0
app/common/service/storage/engine/Server.php

@@ -4,6 +4,8 @@ namespace app\common\service\storage\engine;
 
 
 use app\Request;
 use app\Request;
 use think\Exception;
 use think\Exception;
+use app\common\service\ConfigService;
+use app\common\service\ImageCompressService;
 
 
 /**
 /**
  * 存储引擎抽象类
  * 存储引擎抽象类
@@ -49,11 +51,47 @@ abstract class Server
             'name'     => $this->file->getOriginalName(),
             'name'     => $this->file->getOriginalName(),
             'realPath' => $this->file->getRealPath(),
             'realPath' => $this->file->getRealPath(),
         ];
         ];
+        // 如果是图片文件,进行压缩处理
+        if ($this->isImageFile()) {
+            $compressedPath = $this->compressImage();
+            if ($compressedPath) {
+                $this->fileInfo['realPath'] = $compressedPath;
+                $this->fileInfo['size'] = filesize($compressedPath);
+            }
+        }
         // 生成保存文件名
         // 生成保存文件名
         $this->fileName = $this->buildSaveName();
         $this->fileName = $this->buildSaveName();
     }
     }
 
 
     /**
     /**
+     * 压缩图片
+     */
+    protected function compressImage()
+    {
+
+        // 获取压缩配置(可以从配置文件读取)
+        $quality = ConfigService::get('upload', 'image_quality', 80);
+        $maxWidth = ConfigService::get('upload', 'max_width', 1920);
+        $maxHeight = ConfigService::get('upload', 'max_height', 1080);
+        
+        return ImageCompressService::compress(
+            $this->fileInfo['realPath'],
+            $quality,
+            $maxWidth,
+            $maxHeight
+        );
+    }
+
+    /**
+     * 判断是否为图片文件
+     */
+    protected function isImageFile()
+    {
+        $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
+        return in_array(strtolower($this->fileInfo['ext']), $imageExtensions);
+    }
+
+    /**
      * 设置上传的文件信息
      * 设置上传的文件信息
      * @param string $filePath
      * @param string $filePath
      */
      */