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. Create, resize, crop, encode, and optimize images with a simple fluent API, supporting GD and Imagick, plus drivers and integrations for common storage and HTTP workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation (PHP 8.3+ required):

    composer require intervention/image:^4.0
    

    Publish Laravel config (optional):

    php artisan vendor:publish --provider="Intervention\Image\ImageServiceProvider" --tag=config
    
  2. Basic Usage (Fluent API):

    use Intervention\Image\Facades\Image;
    
    $img = Image::make(public_path('images/original.jpg'))
        ->resize(300, 200)
        ->save(public_path('images/thumbnail.jpg'));
    
  3. First Use Case (Dynamic Thumbnail Generation):

    public function generateThumbnail($filename, $width = 300) {
        return Image::make(storage_path("app/{$filename}"))
            ->resize($width, null, function ($constraint) {
                $constraint->aspectRatio();
            })
            ->save();
    }
    
  4. Key Files to Explore:

    • config/image.php: Driver configuration (GD/Imagick/libvips), quality settings, and cache paths.
    • app/Providers/ImageServiceProvider.php: Laravel service provider for facades.
    • v4 Official Docs: API reference, breaking changes, and examples.

Implementation Patterns

Core Workflows

1. Dynamic Image Processing with Constraints

public function responsiveImage($filename, $maxWidth = 1200) {
    return Image::make(storage_path("app/{$filename}"))
        ->resize(new \Intervention\Image\Constraints\Dimension($maxWidth, null), function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        })
        ->encode('webp', 80)
        ->toResponse();
}

2. Watermarking with Transparency

public function addWatermark($imagePath, $watermarkPath, $outputPath) {
    $img = Image::make($imagePath);
    $watermark = Image::make($watermarkPath)
        ->resize(200, null, function ($constraint) {
            $constraint->aspectRatio();
        })
        ->opacity(50);

    $img->insert($watermark, 'center');
    return $img->save($outputPath);
}

3. Batch Processing with Queues

public function processUploadedImages($userId) {
    $images = UserImage::where('user_id', $userId)
        ->where('processed', false)
        ->get();

    foreach ($images as $image) {
        ProcessImageJob::dispatch($image->path, $image->id);
    }
}

// Job class
public function handle() {
    $img = Image::make(storage_path("app/{$this->path}"))
        ->resize(800, null, function ($constraint) {
            $constraint->aspectRatio();
        })
        ->save();

    UserImage::find($this->imageId)
        ->update(['processed' => true, 'path' => $img->path]);
}

4. Laravel Response Integration

public function getImage(Request $request, $filename) {
    $path = storage_path("app/{$filename}");
    $img = Image::make($path)
        ->resize(1024, null, function ($constraint) {
            $constraint->aspectRatio();
        });

    return response($img->encode(), 200, [
        'Content-Type' => $img->mime(),
        'Cache-Control' => 'public, max-age=31536000',
    ]);
}

5. Driver-Specific Optimization

// In config/image.php
'drivers' => [
    'gd' => [
        'quality' => 90,
        'interlace' => true,
        'optimize' => true,
    ],
    'imagick' => [
        'quality' => 95,
        'sampling' => 'Lanczos',
    ],
],

// Usage
$img = Image::make($path)
    ->driver('imagick') // Force Imagick for high-quality output
    ->resize(1500, null)
    ->save();

Gotchas and Tips

Pitfalls

  1. Driver Compatibility:

    • GD and Imagick may produce different results for complex operations (e.g., text rendering, transparency).
    • Always test critical operations with both drivers if possible.
    • Fix: Use ->driver('imagick') explicitly for consistent results.
  2. Memory Limits:

    • Large images or complex operations (e.g., canvas resizing) can hit PHP memory limits.
    • Fix: Use ->stream() for direct output or process in chunks:
      $img->stream(function ($image) {
          return $image->resize(2000, 2000);
      }, 'jpg', 80);
      
  3. Path Handling:

    • Relative paths in ->font() or ->insert() may break across environments.
    • Fix: Use absolute paths or Laravel's public_path()/storage_path().
  4. Animated Images:

    • GIF/WebP animations may behave unexpectedly with certain operations.
    • Fix: Use ->frameDelay() or ->optimize() for animations:
      $img->optimize()->save();
      
  5. Color Space Inconsistencies:

    • RGB/CMYK conversions may yield unexpected results.
    • Fix: Use ->colorize() or ->adjust() with explicit color spaces:
      $img->colorize(200, 100, 50, 50); // RGBA
      

Debugging Tips

  1. Inspect Image Data:

    $img = Image::make($path);
    dd($img->debug()); // Shows width, height, mime, and driver info
    
  2. Check Driver Availability:

    if (!Image::driversAvailable()) {
        dd(Image::driversAvailable()); // Shows available drivers
    }
    
  3. Handle Exceptions Gracefully:

    try {
        $img = Image::make($path)->resize(100, 100);
    } catch (\Intervention\Image\Exception\NotReadableException $e) {
        Log::error("Image not readable: {$e->getMessage()}");
        return response()->view('errors.image');
    }
    

Performance Optimization

  1. Cache Processed Images:

    $img = Image::cache(function ($image) {
        return $image->resize(800, 600)->sharpen(10);
    }, 'memory', 3600); // Cache for 1 hour
    
  2. Use Efficient Formats:

    • Prefer WebP for modern browsers (smaller file size).
    • Use progressive JPEGs for web:
      $img->encode('jpg', 80, ['progressive' => true]);
      
  3. Batch Operations:

    $images = collect([...]);
    $processed = $images->map(function ($path) {
        return Image::make($path)->resize(400, 400)->encode('webp', 70);
    });
    

Extension Points

  1. Custom Drivers:

    • Extend \Intervention\Image\Driver\DriverInterface for custom backends.
    • Register via ImageManager::extend().
  2. Modify Constraints:

    • Create custom constraint classes by extending \Intervention\Image\Constraints\Constraint.
  3. Add Filters:

    • Implement \Intervention\Image\Filter\FilterInterface for custom effects (e.g., blur, pixelate).
  4. Override Defaults:

    • Publish the config and modify config/image.php for global settings.

Laravel-Specific Tips

  1. Store Processed Images:

    $path = $request->file('image')->store('processed', 'public');
    $img = Image::make(storage_path("app/{$path}"))
        ->resize(1024, 1024)
        ->save();
    
  2. Use Storage Facade:

    $img = Image::make(storage_path('app/' . $request->file('image')->hashName()))
        ->resize(800, 800)
        ->save();
    
  3. Queue Long-Running Tasks:

    ProcessImageJob::dispatch($request->file('image'), $user->id);
    
  4. Leverage Facades:

    // Instead of:
    $img = (new ImageManager())->gd()->read($path);
    
    // Use:
    $img = Image::make($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.
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