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

intervention/image

Intervention Image is a PHP image handling and manipulation library for Laravel and other frameworks. It provides a fluent API for resizing, cropping, encoding, watermarking, and optimizing images, with drivers for GD and Imagick and easy integration via service providers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require intervention/image
    

    Ensure your server has either GD (php-gd) or Imagick (php-imagick) installed.

  2. Basic Usage:

    use Intervention\Image\Facades\Image;
    
    $img = Image::make(public_path('image.jpg'));
    $img->resize(300, 200)->save(public_path('resized.jpg'));
    
  3. First Use Case:

    • Thumbnail Generation:
      $img = Image::make(storage_path('original.jpg'))
                  ->fit(150, 150)
                  ->save(storage_path('thumbnail.jpg'));
      

Where to Look First

  • Official Documentation (v4.x for Laravel 10+)
  • Facade API: Intervention\Image\Facades\Image for quick usage.
  • Driver Selection: Use ImageManager::gd() or ImageManager::imagick() for explicit driver control.

Implementation Patterns

Core Workflows

  1. Image Processing Pipeline:

    $img = Image::make($path)
        ->resize(null, 800, function ($constraint) {
            $constraint->aspectRatio();
        })
        ->watermark(public_path('watermark.png'), 'bottom-right', 10, 10)
        ->encode('jpg', 90)
        ->save($outputPath);
    
  2. Dynamic Resizing with Conditions:

    $img = Image::make($request->file('image'));
    if ($request->input('is_thumbnail')) {
        $img->fit(200, 200);
    } else {
        $img->resize(1200, null, function ($constraint) {
            $constraint->upsize();
        });
    }
    
  3. Batch Processing:

    $files = Storage::disk('s3')->files('images/');
    foreach ($files as $file) {
        $img = Image::make(storage_path("tmp/{$file}"))
            ->resize(800, 600)
            ->save(storage_path("processed/{$file}"));
    }
    

Integration Tips

  • Laravel Filesystem: Use Storage::disk() to read/write images from S3, local storage, etc.

    $img = Image::make(Storage::disk('s3')->path('image.jpg'));
    
  • Jobs/Queues: Offload heavy processing to queues:

    ProcessImageJob::dispatch($imagePath, $outputPath, $resizeTo);
    
  • Middleware: Validate/resize uploads before storage:

    public function handle(Request $request, Closure $next) {
        if ($request->hasFile('image')) {
            $img = Image::make($request->file('image'));
            $img->resize(1024, 1024)->save($request->file('image')->path());
        }
        return $next($request);
    }
    
  • API Responses: Return processed images directly:

    return response($img->encode(), 200, [
        'Content-Type' => $img->mime(),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Driver Incompatibility:

    • GD vs. Imagick: Some features (e.g., advanced filters) require Imagick.
    • Check Availability:
      if (!ImageManager::gd()->check()) {
          throw new \RuntimeException('GD library is not installed.');
      }
      
  2. Memory Limits:

    • Large images may hit PHP’s memory_limit. Use libvips (if available) for memory efficiency:
      $img = Image::make($path)->driver('vips')->resize(...);
      
  3. Path Handling:

    • Absolute paths are required for fonts/watermarks:
      $img->text('Hello', public_path('fonts/arial.ttf'), 20)->draw();
      
  4. Animated Images (GIF/WEBP):

    • Decoding animations requires explicit configuration:
      $img = Image::make($path)->decode();
      foreach ($img->frames() as $frame) {
          $frame->save("frame_{$frame->index}.jpg");
      }
      
  5. Color Space Issues:

    • CMYK images may render incorrectly. Convert to RGB first:
      $img->colorize(function ($color) {
          return $color->convert('rgb');
      });
      

Debugging Tips

  • Inspect Image Data:

    $img->debug()->save('debug.jpg'); // Shows bounding box, dimensions
    var_dump($img->colors()); // Inspect palette
    
  • Error Handling: Wrap operations in try-catch:

    try {
        $img->resize(10000, 10000); // May fail for small images
    } catch (\Intervention\Image\Exception\NotReadableException $e) {
        Log::error($e->getMessage());
    }
    
  • Driver-Specific Quirks:

    • GD: Slower for complex operations but widely compatible.
    • Imagick: Faster but requires imagick extension.
    • Libvips: Best for performance but less common.

Extension Points

  1. Custom Drivers: Extend Intervention\Image\Driver\DriverInterface for new backends (e.g., Cloudinary).

  2. Modifier Chaining: Create reusable modifier chains:

    $img->apply(function ($img) {
        $img->resize(800, 600)->sharpen(10);
    });
    
  3. Color Manipulation: Use the new color system (v4+) for advanced effects:

    $img->colorize(function ($color) {
        return $color->adjust()->lightness(0.2);
    });
    
  4. Event Listeners: Hook into image processing events (e.g., image.saving):

    event(new ImageSaving($img, $path, $format));
    

Performance Optimizations

  • Cache Drivers:

    $img = Image::cache(function ($image) {
        $image->resize(1000, 1000);
    }, 'unique_key')->response();
    
  • Lazy Loading: Defer processing until response:

    return Image::make($path)->resize(800, 600)->stream();
    
  • Format-Specific Optimizations:

    $img->encode('jpg', 80, ['quality' => 80, 'progressive' => true]);
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai