Installation Run:
composer require duguncom/imagebundle:~2.0
Add to config/bundles.php (Symfony 4+):
return [
// ...
Duguncom\ImageBundle\DuguncomImageBundle::class => ['all' => true],
];
Configuration Publish the default config:
php artisan vendor:publish --tag=duguncom-image-config
Edit config/duguncom_image.php to define:
default_driver (e.g., gd, imagick).storage paths (e.g., cache_path, public_path).['jpg', 'png']).First Use Case Generate a thumbnail in a controller:
use Duguncom\ImageBundle\ImageManager;
public function uploadImage(Request $request, ImageManager $imageManager)
{
$file = $request->file('image');
$path = $imageManager->make($file->getRealPath())
->resize(200, 200)
->save('uploads/thumbs/' . $file->getClientOriginalName());
return redirect()->back()->with('success', $path);
}
Image Processing Pipeline
Chain methods in ImageManager:
$imageManager->make($filePath)
->resize(800, 600) // Width, height
->crop(200, 200, 100, 100) // Width, height, x, y
->rotate(90) // Degrees
->watermark('logo.png', 0.2, 0.2) // Path, opacity, position
->save($destination);
Dynamic Thumbnails Use a service to generate multiple sizes:
// config/duguncom_image.php
'sizes' => [
'thumb' => ['width' => 200, 'height' => 200],
'large' => ['width' => 1000, 'height' => null], // Auto-height
];
// In controller
foreach (config('duguncom_image.sizes') as $name => $size) {
$imageManager->make($file)
->resize($size['width'], $size['height'])
->save("uploads/{$name}/{$file->getClientOriginalName()}");
}
Form Integration Use a custom field type for automatic processing:
{{ form_widget(form.image, {
'attr': {
'data-dugun-image': {
'resize': '200x200',
'watermark': 'logo.png'
}
}
}) }}
(Note: Requires JavaScript integration; see "Gotchas" for limitations.)
Batch Processing Process multiple files in a loop:
foreach ($request->file('images') as $file) {
$imageManager->make($file->getRealPath())
->resize(500, 500)
->save("batch/{$file->hashName()}");
}
Symfony Events
Trigger processing on upload via KernelEvents::REQUEST:
// src/EventListener/ImageUploadListener.php
public function onKernelRequest(GetResponseEvent $event)
{
if ($event->isMasterRequest() && $request = $event->getRequest()) {
if ($request->isMethod('POST') && $request->hasFile('image')) {
$this->processUpload($request);
}
}
}
Flysystem Adapter Store processed images in cloud storage (e.g., S3):
$imageManager->make($file)
->resize(300, 300)
->save($storage->writeStream('remote/path.jpg', $stream));
Validation Rules Extend Laravel’s validation to check image dimensions:
use Duguncom\ImageBundle\Rules\Dimensions;
$request->validate([
'image' => ['required', new Dimensions(['min_width' => 100, 'min_height' => 100])],
]);
Caching Cache processed images to avoid reprocessing:
$cacheKey = md5($filePath . '_thumb');
if (!$cachedPath = cache()->get($cacheKey)) {
$cachedPath = $imageManager->make($filePath)->resize(100, 100)->save('cache/');
cache()->put($cacheKey, $cachedPath, now()->addDays(7));
}
Driver Dependencies
sudo apt-get install php-gd or pecl install imagick).config/duguncom_image.php:
'drivers' => [
'gd' => ['enabled' => extension_loaded('gd')],
'imagick' => ['enabled' => extension_loaded('imagick')],
],
RuntimeException.File Permissions
storage/app/public and storage/app/cache are writable:
chmod -R 775 storage/
Memory Limits
memory_limit. Increase in .env:
MEMORY_LIMIT=1024M
Twig/JavaScript Limitation
The data-dugun-image attribute in Twig is not natively supported. Use a custom JavaScript library like Blueimp’s jQuery File Upload for client-side processing.
Path Handling
storage_path('app/public/thumb.jpg')) to avoid issues.$path = str_replace('\\', '/', $filePath);
Deprecated Methods
->saveAs() (deprecated in v2.0). Use ->save($path) instead.Enable Logging
Add to config/duguncom_image.php:
'debug' => true,
Logs will appear in storage/logs/laravel.log.
Check Processed Images Verify files are saved in the correct directory. Use:
$imageManager->make($file)->debug()->save($path);
(Note: debug() is undocumented but often works in v2.0.)
Common Errors
| Error Message | Solution |
|---|---|
Driver not found |
Install GD/Imagick or set default_driver in config. |
File not found |
Check $file->getRealPath() vs. $file->getPathname(). |
Permission denied |
Run chmod -R 775 storage/ and check storage/app. |
Image could not be resized |
Ensure the image is a valid format (JPG, PNG, etc.). |
Call to undefined method |
Update to the latest v2.x or check method names against the source. |
Custom Drivers
Extend Duguncom\ImageBundle\Driver\DriverInterface to add support for new libraries (e.g., Intervention Image):
namespace App\ImageBundle\Driver;
use Duguncom\ImageBundle\Driver\DriverInterface;
use Intervention\Image\ImageManager as InterventionManager;
class InterventionDriver implements DriverInterface
{
public function __construct(private InterventionManager $manager) {}
public function resize($path, $width, $height) {
return $this->manager->make($path)->resize($width, $height)->save();
}
// Implement other methods...
}
Register in config/duguncom_image.php:
'drivers' => [
'intervention' => [
'class' => App\ImageBundle\Driver\InterventionDriver::class,
'enabled' => true,
],
],
**Custom
How can I help you explore Laravel packages today?