moonsflyer 4 miesięcy temu
rodzic
commit
077cddc9ab
1 zmienionych plików z 48 dodań i 11 usunięć
  1. 48 11
      app/common/service/ImageCompressService.php

+ 48 - 11
app/common/service/ImageCompressService.php

@@ -17,6 +17,10 @@ class ImageCompressService
     public static function compress($sourcePath, $quality = 80, $maxWidth = 1920, $maxHeight = 1080)
     public static function compress($sourcePath, $quality = 80, $maxWidth = 1920, $maxHeight = 1080)
     {
     {
         try {
         try {
+            // 验证输入参数
+            if (empty($sourcePath)) {
+                throw new Exception('源文件路径不能为空');
+            }
             outFileLog($sourcePath,'upload_img','$sourcePath1');
             outFileLog($sourcePath,'upload_img','$sourcePath1');
             // 获取图片信息
             // 获取图片信息
             $imageInfo = getimagesize($sourcePath);
             $imageInfo = getimagesize($sourcePath);
@@ -96,17 +100,50 @@ class ImageCompressService
      */
      */
     private static function createImageFromType($path, $type)
     private static function createImageFromType($path, $type)
     {
     {
-        switch ($type) {
-            case IMAGETYPE_JPEG:
-                return imagecreatefromjpeg($path);
-            case IMAGETYPE_PNG:
-                return imagecreatefrompng($path);
-            case IMAGETYPE_GIF:
-                return imagecreatefromgif($path);
-            case IMAGETYPE_WEBP:
-                return imagecreatefromwebp($path);
-            default:
-                return false;
+        // 检查文件是否存在
+        if (!file_exists($path)) {
+            throw new Exception('图片文件不存在: ' . $path);
+        }
+
+        // 检查文件是否可读
+        if (!is_readable($path)) {
+            throw new Exception('图片文件无法读取: ' . $path);
+        }
+
+        // 检查GD扩展
+        if (!extension_loaded('gd')) {
+            throw new Exception('GD扩展未安装');
+        }
+
+        try {
+            switch ($type) {
+                case IMAGETYPE_JPEG:
+                    $image = imagecreatefromjpeg($path);
+                    break;
+                case IMAGETYPE_PNG:
+                    $image = imagecreatefrompng($path);
+                    break;
+                case IMAGETYPE_GIF:
+                    $image = imagecreatefromgif($path);
+                    break;
+                case IMAGETYPE_WEBP:
+                    if (!function_exists('imagecreatefromwebp')) {
+                        throw new Exception('WebP格式不支持');
+                    }
+                    $image = imagecreatefromwebp($path);
+                    break;
+                default:
+                    throw new Exception('不支持的图片格式: ' . $type);
+            }
+
+            if (!$image) {
+                throw new Exception('创建图片资源失败,可能是内存不足或文件损坏');
+            }
+
+            return $image;
+
+        } catch (Exception $e) {
+            throw new Exception('图片处理失败: ' . $e->getMessage());
         }
         }
     }
     }