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 Laravel Package

spatie/image

Expressive PHP image manipulation with a fluent API. Resize, crop, rotate, apply filters (greyscale, brightness, sharpen), adjust quality, and auto-orient images. Load from a path and save in place or to a new file.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/image
    

    Ensure exif PHP extension is enabled (required since v1.5.3).

  2. First Use Case: Resize an image while preserving aspect ratio:

    use Spatie\Image\Image;
    
    Image::load(public_path('original.jpg'))
        ->width(300)
        ->height(300)
        ->save(public_path('resized.jpg'));
    
  3. Key Documentation:


Implementation Patterns

Core Workflows

  1. Image Processing Pipeline:

    // Chain operations for efficiency
    Image::load($path)
        ->resize(800, 600, function ($constraint) {
            $constraint->aspectRatio();
        })
        ->watermark(public_path('watermark.png'), 0.2)
        ->save($outputPath);
    
  2. Dynamic Thumbnail Generation:

    // Generate multiple sizes in a single pass
    $image = Image::load($originalPath);
    $image->resize(100, 100)->save($thumbnailSmall);
    $image->reset()->resize(300, 300)->save($thumbnailLarge);
    
  3. Batch Processing:

    // Process all images in a directory
    foreach (Storage::disk('public')->files('uploads') as $file) {
        $path = storage_path("app/{$file}");
        Image::load($path)
            ->resize(1200, null, function ($constraint) {
                $constraint->upsize();
            })
            ->save($path);
    }
    

Integration Tips

  1. Laravel Filesystem: Use Storage::disk() for cloud storage (S3, etc.):

    Image::load(Storage::disk('s3')->path('original.jpg'))
        ->resize(400, 400)
        ->save(Storage::disk('s3')->path('processed.jpg'));
    
  2. Model Observers: Automate processing on upload:

    // app/Observers/ImageObserver.php
    public function saved(UploadedFile $file) {
        Image::load($file->path())
            ->resize(800, 600)
            ->save($file->path());
    }
    
  3. Queue Jobs: Offload heavy processing:

    // app/Jobs/ProcessImage.php
    public function handle() {
        Image::load($this->path)
            ->resize(1500, 1500)
            ->save($this->path);
    }
    
  4. Custom Drivers: Extend for specialized needs (e.g., PDF support):

    // app/Drivers/PdfDriver.php
    class PdfDriver extends \Spatie\Image\Support\Drivers\Driver {
        public function __construct() {
            $this->driverName = 'pdf';
        }
        // Implement required methods
    }
    

Gotchas and Tips

Common Pitfalls

  1. Driver Selection:

    • GD vs Imagick: Imagick offers better quality but requires installation. GD is default if Imagick is unavailable.
    • Vips Driver: New in v3.9.0, ideal for large images (memory-efficient) but requires libvips:
      Image::load($path)->driver('vips')->resize(2000, 2000);
      
  2. EXIF Orientation:

    • GD driver may mishandle orientations (fixed in v3.9.4). Use Imagick for reliability:
      Image::load($path)->driver('imagick')->orientation();
      
  3. File Extensions:

    • Always specify formats explicitly when saving:
      // Avoid: Image::load()->save('output'); // May lose format
      Image::load()->save('output.webp'); // Force format
      
  4. Quality Settings:

    • JPEG quality (1-100) and PNG compression (0-9) are critical:
      Image::load()->quality(85)->save(); // Balanced JPEG quality
      
  5. Canvas Resizing:

    • resizeCanvas() vs resize():
      // resizeCanvas: Expands canvas (adds padding)
      // resize: Crops/stretches to fit
      

Debugging Tips

  1. Driver-Specific Issues:

    • Check phpinfo() for installed drivers:
      if (!extension_loaded('imagick')) {
          throw new \RuntimeException('Imagick extension required');
      }
      
  2. Memory Limits:

    • Use Vips driver for large files (>10MB):
      Image::load()->driver('vips')->resize(4000, 4000);
      
  3. Error Handling:

    • Wrap operations in try-catch:
      try {
          Image::load($path)->resize(100, 100)->save();
      } catch (\Spatie\Image\Exceptions\CouldNotLoadImage $e) {
          Log::error("Invalid image: {$path}");
      }
      

Performance Optimization

  1. Batch Processing:

    • Process multiple images in a single script to avoid overhead:
      $images = collect([...]);
      $images->each(fn($path) => Image::load($path)->resize(500, 500)->save($path));
      
  2. Caching:

    • Cache processed images to avoid reprocessing:
      if (!file_exists($cachedPath)) {
          Image::load($original)->resize(300, 300)->save($cachedPath);
      }
      
  3. Lazy Loading:

    • Defer operations until save():
      $image = Image::load($path)->resize(200, 200); // No processing yet
      $image->save(); // Triggers processing
      

Extension Points

  1. Custom Filters:

    • Extend the Filter class for reusable operations:
      class CustomFilter extends \Spatie\Image\Filters\Filter {
          public function apply($image) {
              $image->brightness(10)->contrast(20);
              return $image;
          }
      }
      
  2. Event Hooks:

    • Listen for image events (e.g., post-resize):
      Image::load($path)->on('post-resize', function () {
          Log::info('Image resized successfully');
      });
      
  3. Format-Specific Logic:

    • Override save() behavior per format:
      Image::load()->save(function ($image, $path) {
          if (str_ends_with($path, '.webp')) {
              $image->quality(70);
          }
          $image->save($path);
      });
      
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony