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

intervention/image-laravel

Laravel integration for Intervention Image. Adds a service provider, facade, and publishable config for app-wide image settings (GD or Imagick). Install via Composer and manage image processing consistently across your Laravel app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require intervention/image-laravel
    

    No additional setup is required for basic usage.

  2. First Use Case: Resizing an Uploaded Image

    use Intervention\Image\Laravel\Facades\Image;
    
    $image = Image::make(request()->file('avatar'))
        ->resize(300, 200)
        ->save(storage_path('app/avatars/' . auth()->id() . '.jpg'));
    
  3. Publish Configuration (Optional)

    php artisan vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"
    

    Edit config/image.php to customize driver (GD/Imagick) and global options like autoOrientation.


Implementation Patterns

Core Workflows

  1. Facade-Based Image Processing Use the Image facade for concise syntax:

    // Resize and save
    Image::make($file)->resize(800, 600)->save($path);
    
    // Apply filters
    Image::make($file)->grayscale()->watermark($watermark, 0.2)->save($path);
    
  2. Dynamic Responses with Macros Streamline API/image endpoints:

    return response()->image(
        Image::make($file)->resize(100, 100),
        'webp',
        quality: 80
    );
    
  3. Batch Processing Process multiple images in a loop:

    foreach ($request->file('images') as $file) {
        $path = 'processed/' . $file->hashName();
        Image::make($file)->resize(400, 400)->save($path);
    }
    

Integration Tips

  • Storage Integration Combine with Laravel’s Storage facade for cloud storage (S3, etc.):

    use Illuminate\Support\Facades\Storage;
    Storage::put('optimized/' . $file->hashName(), $image->encode());
    
  • Validation Validate image dimensions before processing:

    $image = Image::make($file);
    if ($image->width() > 2000) {
        abort(422, 'Image too large');
    }
    
  • Caching Cache processed images to avoid reprocessing:

    $cacheKey = 'thumb_' . md5($file->path());
    if (!Cache::has($cacheKey)) {
        Cache::put($cacheKey, $image->encode(), now()->addHours(1));
    }
    
  • Queue Jobs Offload processing to queues for large files:

    ProcessImageJob::dispatch($file, $targetSize);
    

Gotchas and Tips

Pitfalls

  1. Driver Dependencies

    • GD vs. Imagick: Ensure your PHP installation has the correct driver (gd or imagick extension). Test with:
      php -m | grep -E 'gd|imagick'
      
    • Fallback: Use try-catch for driver-specific features:
      try {
          Image::make($file)->imagick()->resize(...);
      } catch (\Exception $e) {
          Image::make($file)->resize(...); // Fallback to GD
      }
      
  2. Memory Limits

    • Large images may hit PHP’s memory_limit. Increase it temporarily:
      ini_set('memory_limit', '512M');
      
    • Use ->resize() before other operations to reduce memory usage.
  3. File Paths

    • Absolute Paths: Always use storage_path(), public_path(), or real_path() to avoid issues with relative paths.
  4. Console Context

    • The response()->image() macro is disabled in console commands. Use manual encoding:
      $image->encode()->save($path);
      

Debugging

  1. Check Image Data Log image properties for debugging:

    $image = Image::make($file);
    \Log::debug([
        'width' => $image->width(),
        'height' => $image->height(),
        'mime' => $image->mime(),
    ]);
    
  2. Validate Input Ensure files are images before processing:

    if (!in_array($file->getClientMimeType(), ['image/jpeg', 'image/png'])) {
        abort(422, 'Invalid image type');
    }
    
  3. Test Drivers Verify driver functionality in a test:

    public function test_driver()
    {
        $this->assertEquals(
            config('image.driver'),
            \Intervention\Image\Drivers\Gd\Driver::class
        );
    }
    

Extension Points

  1. Custom Drivers Extend the package by binding a custom driver in the service provider:

    $this->app->bind(
        \Intervention\Image\ImageManager::class,
        function ($app) {
            $manager = new \Intervention\Image\ImageManager(new \App\Drivers\CustomDriver());
            return $manager;
        }
    );
    
  2. Global Filters Add reusable filters via a trait or helper:

    // app/Helpers/ImageHelper.php
    if (!function_exists('applyWatermark')) {
        function applyWatermark($image, $watermarkPath, $opacity = 0.5) {
            return $image->insert($watermarkPath, 'bottom-right')->opacity($opacity);
        }
    }
    
  3. Event Listeners Trigger events for image processing (e.g., logging, analytics):

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        'intervention.image.processed' => [
            \App\Listeners\LogImageProcessing::class,
        ],
    ];
    
  4. Testing Mock the facade in tests:

    Image::shouldReceive('make')
        ->once()
        ->andReturn($mockImage);
    

Configuration Quirks

  1. Environment Overrides Override driver settings in .env:

    IMAGE_DRIVER=imagick
    
  2. Quality Settings Adjust quality parameter for output (default: 75). Higher values (90+) for lossless formats like PNG.

  3. Animation Handling Disable decodeAnimation in config/image.php if working with static images to avoid performance overhead.

  4. Background Color Set backgroundColor in config to handle transparency consistently (e.g., 'ffffff' for white).

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
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
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests