Created
January 30, 2026 15:17
-
-
Save ivanmercedes/2afae2a5806aaf3485ee5ea4e276f0b5 to your computer and use it in GitHub Desktop.
Laravel Image Optimizer Service (Intervention Image)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Services; | |
| use Intervention\Image\Drivers\Imagick\Driver; | |
| use Intervention\Image\ImageManager; | |
| class ImageOptimizer | |
| { | |
| protected ImageManager $manager; | |
| public function __construct() | |
| { | |
| // specific driver provided | |
| $this->manager = new ImageManager(new Driver); | |
| } | |
| /** | |
| * Resize and optimize an image in place. | |
| */ | |
| public function optimize(string $absolutePath, int $maxWidth = 980, int $quality = 90): string | |
| { | |
| if (! file_exists($absolutePath)) { | |
| return $absolutePath; | |
| } | |
| $image = $this->manager->read($absolutePath); | |
| // Resize if wider than max width, preserving aspect ratio | |
| if ($image->width() > $maxWidth) { | |
| $image->scale(width: $maxWidth); | |
| } | |
| $extension = strtolower(pathinfo($absolutePath, PATHINFO_EXTENSION)); | |
| // If GIF, preserve format/animation | |
| if ($extension === 'gif') { | |
| $image->toGif()->save($absolutePath); | |
| return $absolutePath; | |
| } | |
| // Force .jpg extension for others | |
| $pathInfo = pathinfo($absolutePath); | |
| $newPath = $pathInfo['dirname'].'/'.$pathInfo['filename'].'.jpg'; | |
| // Encode as JPG with quality | |
| $image->toJpeg($quality)->save($newPath); | |
| if ($newPath !== $absolutePath) { | |
| unlink($absolutePath); | |
| } | |
| return $newPath; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment