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

Imagebundle Laravel Package

duguncom/imagebundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run:

    composer require duguncom/imagebundle:~2.0
    

    Add to config/bundles.php (Symfony 4+):

    return [
        // ...
        Duguncom\ImageBundle\DuguncomImageBundle::class => ['all' => true],
    ];
    
  2. 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).
    • Allowed file types (e.g., ['jpg', 'png']).
  3. 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);
    }
    

Implementation Patterns

Core Workflows

  1. 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);
    
  2. 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()}");
    }
    
  3. 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.)

  4. 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()}");
    }
    

Integration Tips

  1. 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);
            }
        }
    }
    
  2. Flysystem Adapter Store processed images in cloud storage (e.g., S3):

    $imageManager->make($file)
        ->resize(300, 300)
        ->save($storage->writeStream('remote/path.jpg', $stream));
    
  3. 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])],
    ]);
    
  4. 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));
    }
    

Gotchas and Tips

Pitfalls

  1. Driver Dependencies

    • GD vs. Imagick: Ensure the PHP extension is installed (sudo apt-get install php-gd or pecl install imagick).
    • Fallback: Configure a default driver in config/duguncom_image.php:
      'drivers' => [
          'gd' => ['enabled' => extension_loaded('gd')],
          'imagick' => ['enabled' => extension_loaded('imagick')],
      ],
      
    • Error: If neither driver is enabled, the bundle throws RuntimeException.
  2. File Permissions

    • Ensure storage/app/public and storage/app/cache are writable:
      chmod -R 775 storage/
      
    • Symptom: Silent failures or corrupted images.
  3. Memory Limits

    • Large images may hit PHP’s memory_limit. Increase in .env:
      MEMORY_LIMIT=1024M
      
    • Workaround: Process images in chunks or use Imagick (more memory-efficient).
  4. 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.

  5. Path Handling

    • Absolute vs. Relative: Always use absolute paths (e.g., storage_path('app/public/thumb.jpg')) to avoid issues.
    • Windows Paths: Escape backslashes or use forward slashes:
      $path = str_replace('\\', '/', $filePath);
      
  6. Deprecated Methods

    • Avoid ->saveAs() (deprecated in v2.0). Use ->save($path) instead.

Debugging

  1. Enable Logging Add to config/duguncom_image.php:

    'debug' => true,
    

    Logs will appear in storage/logs/laravel.log.

  2. 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.)

  3. 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.

Extension Points

  1. 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,
        ],
    ],
    
  2. **Custom

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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle