Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Image Optimizer Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

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.

Implementation Patterns

  • Standard optimization pipeline: Use OptimizerChainFactory::create() for automatic binary detection and sensible defaults. Ideal for cron jobs, batch processing, or upload handlers.
  • Preserve originals: Pass a second argument to optimize($source, $destination) to avoid overwriting source files—essential for user-uploaded content or versioned assets.
  • Custom optimizer chains: Build chains manually for fine-grained control (e.g., only JPEG optimization in a JPEG-heavy workflow):
$chain = (new OptimizerChain)
    ->addOptimizer(new Jpegoptim(['--strip-all', '--all-progressive', '-m85']));
  • Timeouts & logging: Set setTimeout() for slow binaries (e.g., avifenc), and inject a PSR-3 logger (e.g., Monolog) to debug failures in production.
  • Custom optimizer classes: Extend Optimizer interface to integrate in-house tools (e.g., mozjpeg CLI) and register them via addOptimizer().

Common use cases:

  • Laravel: hook into Model::saved or UploadedFile::store() to optimize assets.
  • CMS batch jobs: process entire directories via Artisan commands.
  • API services: integrate into image proxy endpoints to serve optimized variants on-the-fly.

Gotchas and Tips

  • Silent failures: By default, the package swallows exceptions. Always configure logging initially (useLogger()) to catch missing binaries or permission errors (e.g., cwebp not in $PATH).
  • Binary dependencies: Even if installed, binaries like avifenc require ≥v0.9.3; check versions with php artisan tinker (exec('avifenc --version')) before production.
  • SVG risks: SVGO can break interactivity or IDs—disable cleanupIDs and removeViewBox intentionally, and test SVGs post-optimization.
  • Non-destructive testing: Use a test directory with optimize($source, $dest) to benchmark quality loss vs. file size gains—especially critical for AVIF/WEBP.
  • Performance tuning: setTimeout() applies per optimizer, not the full chain; set timeouts conservatively (e.g., 15–30s) for AVIF, which can be CPU-intensive.
  • Path validation: Never pass user-supplied paths directly—resolve to absolute paths first (realpath()) to avoid command injection.
  • Platform differences: macOS/Linux binaries often differ from Windows; consider Dockerizing with pre-installed tools for consistency.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport