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.
Installation
composer require intervention/image-laravel
No additional setup is required for basic usage.
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'));
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.
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);
Dynamic Responses with Macros Streamline API/image endpoints:
return response()->image(
Image::make($file)->resize(100, 100),
'webp',
quality: 80
);
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);
}
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);
Driver Dependencies
gd or imagick extension). Test with:
php -m | grep -E 'gd|imagick'
try-catch for driver-specific features:
try {
Image::make($file)->imagick()->resize(...);
} catch (\Exception $e) {
Image::make($file)->resize(...); // Fallback to GD
}
Memory Limits
memory_limit. Increase it temporarily:
ini_set('memory_limit', '512M');
->resize() before other operations to reduce memory usage.File Paths
storage_path(), public_path(), or real_path() to avoid issues with relative paths.Console Context
response()->image() macro is disabled in console commands. Use manual encoding:
$image->encode()->save($path);
Check Image Data Log image properties for debugging:
$image = Image::make($file);
\Log::debug([
'width' => $image->width(),
'height' => $image->height(),
'mime' => $image->mime(),
]);
Validate Input Ensure files are images before processing:
if (!in_array($file->getClientMimeType(), ['image/jpeg', 'image/png'])) {
abort(422, 'Invalid image type');
}
Test Drivers Verify driver functionality in a test:
public function test_driver()
{
$this->assertEquals(
config('image.driver'),
\Intervention\Image\Drivers\Gd\Driver::class
);
}
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;
}
);
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);
}
}
Event Listeners Trigger events for image processing (e.g., logging, analytics):
// app/Providers/EventServiceProvider.php
protected $listen = [
'intervention.image.processed' => [
\App\Listeners\LogImageProcessing::class,
],
];
Testing Mock the facade in tests:
Image::shouldReceive('make')
->once()
->andReturn($mockImage);
Environment Overrides
Override driver settings in .env:
IMAGE_DRIVER=imagick
Quality Settings
Adjust quality parameter for output (default: 75). Higher values (90+) for lossless formats like PNG.
Animation Handling
Disable decodeAnimation in config/image.php if working with static images to avoid performance overhead.
Background Color
Set backgroundColor in config to handle transparency consistently (e.g., 'ffffff' for white).
How can I help you explore Laravel packages today?