contao/image
Contao Image is a PHP library for generating and manipulating images for Contao projects. It provides helpers for resizing, cropping, and creating responsive image variants, integrating with Contao’s image pipeline to deliver optimized outputs.
Installation
composer require contao/image
Ensure your project has PHP 8.1+ and a supported Laravel version (8.x+).
Basic Usage
use Contao\Image\Image;
$image = new Image('path/to/image.jpg');
$image->resize(300, 200); // Resize with width/height
$image->save('path/to/output.jpg');
First Use Case Dynamically generate thumbnails for uploaded files in a Laravel storage system:
use Contao\Image\Image;
use Illuminate\Support\Facades\Storage;
$file = request()->file('image');
$path = $file->store('uploads');
$image = new Image(storage_path('app/' . $path));
$image->resize(200, 200)->crop('center')->save(storage_path('app/thumbs/' . $path));
src/Contao/Image/Image.php for core methods.tests/ directory in the package for usage patterns.vendor/contao/image/README.md for Laravel-specific notes.Dynamic Image Processing
// In a Laravel controller or service
public function processImage(Request $request) {
$image = new Image($request->file('image')->path());
$image->resize(800, 600)->quality(85)->save(storage_path('processed/' . $request->file('image')->hashName()));
return response()->json(['success' => true]);
}
Batch Processing
use Contao\Image\Image;
use Illuminate\Support\Facades\Storage;
$files = Storage::files('uploads');
foreach ($files as $file) {
$image = new Image(storage_path('app/' . $file));
$image->resize(400, 400)->save(storage_path('app/thumbs/' . $file));
}
Integration with Laravel Filesystem
// Custom Filesystem Adapter for Contao Image
Storage::extend('contao', function ($app) {
return new ContaoImageAdapter($app['files'], $app['config']);
});
// Usage:
Storage::disk('contao')->put('image.jpg', $image->getData());
Service Provider Binding
// In AppServiceProvider
public function register() {
$this->app->bind(Image::class, function ($app) {
return new Image($app['path.storage'] . '/app/uploads/image.jpg');
});
}
Middleware for Image Processing
public function handle($request, Closure $next) {
if ($request->hasFile('image')) {
$image = new Image($request->file('image')->path());
$image->resize(1024, 768)->save(storage_path('temp/' . $request->file('image')->hashName()));
}
return $next($request);
}
Eloquent Model Observers
// In UserObserver
public function saved(User $user) {
if ($user->profile_image) {
$image = new Image(storage_path('app/' . $user->profile_image));
$image->resize(300, 300)->save(storage_path('app/thumbs/' . $user->profile_image));
}
}
Queue Jobs for Async Processing
// ProcessImageJob.php
public function handle() {
$image = new Image(storage_path('app/uploads/' . $this->file));
$image->resize(1200, 800)->save(storage_path('app/processed/' . $this->file));
}
// Dispatch
ProcessImageJob::dispatch($file->hashName());
Memory Limits
memory_limit. Use ->optimize() or chunk processing for big files.memory_limit in php.ini or process images in smaller batches.File Path Handling
Image class expects absolute paths. Relative paths may fail silently.storage_path() or public_path():
$image = new Image(storage_path('app/uploads/' . $file));
GD vs. Imagick
Image::setDriver('gd'); // or 'imagick'
Case Sensitivity
.JPG vs .jpg) may cause issues on case-sensitive systems.$path = strtolower($path);
Permission Issues
storage/app/thumbs) requires proper permissions.chmod -R 775 storage/ or use Laravel’s storage:link.Check Supported Formats
if (!Image::isSupported('path/to/image.webp')) {
throw new \Exception('Unsupported format');
}
Log Errors
try {
$image->resize(1000, 1000);
} catch (\Exception $e) {
\Log::error('Image processing failed: ' . $e->getMessage());
}
Verify Image Data
$image = new Image('path/to/image.jpg');
\Log::info([
'width' => $image->getWidth(),
'height' => $image->getHeight(),
'mime' => $image->getMimeType(),
]);
Custom Filters
Create a decorator for Image:
class CustomImage extends Image {
public function applyCustomFilter() {
$this->applyFilter('some_custom_filter');
}
}
Laravel Facade Add a facade for convenience:
// In config/app.php
'aliases' => [
'Image' => Contao\Facades\Image::class,
];
// Usage:
Image::make('path')->resize(500, 500);
Blade Directives
// In AppServiceProvider
Blade::directive('image', function ($expression) {
return "<?php echo (new \\Contao\\Image\\Image({$expression}))->resize(200, 200)->toHtml(); ?>";
});
// Usage in Blade:
<img src="{{ image('path/to/image.jpg') }}">
Cache Busting Append a hash to processed images to bypass cache:
$hash = md5_file($image->getPath());
$image->save(storage_path("app/thumbs/{$hash}_{$file}"));
Reuse Instances
Avoid recreating Image objects for the same file:
static $cache = [];
$image = $cache[$path] ?? new Image($path);
Lazy Loading Process images only when needed (e.g., in a view):
$imagePath = storage_path('app/uploads/' . $file);
$image = new Image($imagePath);
if ($shouldResize) {
$image->resize(600, 400);
}
Use ->getData() for In-Memory Processing
Avoid saving intermediate files:
$data = $image->resize(100, 100)->getData();
Storage::disk('s3')->put('thumb.jpg', $data);
How can I help you explore Laravel packages today?