1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class ImageOptimizer { public static function optimizeImage($imagePath, $maxWidth = 800, $quality = 85) { $info = getimagesize($imagePath); $width = $info[0]; $height = $info[1]; if ($width > $maxWidth) { $newHeight = ($maxWidth * $height) / $width; return self::resizeImage($imagePath, $maxWidth, $newHeight, $quality); } return $imagePath; } private static function resizeImage($imagePath, $newWidth, $newHeight, $quality) { $image = imagecreatefromjpeg($imagePath); $resized = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($resized, $image, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($image), imagesy($image)); $outputPath = str_replace('.jpg', '_optimized.jpg', $imagePath); imagejpeg($resized, $outputPath, $quality); imagedestroy($image); imagedestroy($resized); return $outputPath; } }
|
文章评论 (0)