spatie/image-optimizer
Optimize PNG, JPG, WebP, AVIF, SVG and GIF images in PHP by running them through a chain of installed binaries (jpegoptim, optipng, pngquant, svgo, etc.). Automatically detects available tools and overwrites files with smaller optimized versions.
Install the package with composer require spatie/image-optimizer, then ensure all required CLI tools (e.g., jpegoptim, optipng, pngquant, svgo, gifsicle, cwebp, avifenc) are installed on your system—follow the OS-specific instructions in the README. The fastest way to get started is:
use Spatie\ImageOptimizer\OptimizerChainFactory;
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize('/path/to/image.jpg'); // overwrites original
For image resizing + optimization workflows (e.g., after uploading), integrate with libraries like spatie/image—load and resize first, then optimize the output.
OptimizerChainFactory::create() for automatic binary detection and sensible defaults. Ideal for cron jobs, batch processing, or upload handlers.optimize($source, $destination) to avoid overwriting source files—essential for user-uploaded content or versioned assets.$chain = (new OptimizerChain)
->addOptimizer(new Jpegoptim(['--strip-all', '--all-progressive', '-m85']));
setTimeout() for slow binaries (e.g., avifenc), and inject a PSR-3 logger (e.g., Monolog) to debug failures in production.Optimizer interface to integrate in-house tools (e.g., mozjpeg CLI) and register them via addOptimizer().Common use cases:
Model::saved or UploadedFile::store() to optimize assets.useLogger()) to catch missing binaries or permission errors (e.g., cwebp not in $PATH).avifenc require ≥v0.9.3; check versions with php artisan tinker (exec('avifenc --version')) before production.cleanupIDs and removeViewBox intentionally, and test SVGs post-optimization.optimize($source, $dest) to benchmark quality loss vs. file size gains—especially critical for AVIF/WEBP.setTimeout() applies per optimizer, not the full chain; set timeouts conservatively (e.g., 15–30s) for AVIF, which can be CPU-intensive.realpath()) to avoid command injection.How can I help you explore Laravel packages today?