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

bigyouth/image-resizer-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies Run composer require bigyouth/image-resizer-bundle liip/imagine-bundle to install the bundle and its dependency. Verify liip/imagine-bundle is configured in config/packages/liip_imagine.yaml (Symfony 5+) or app/config/config.yml (older versions) with a default filter set (no predefined sizes).

  2. Register the Bundle Add new Bigyouth\BigyouthImageResizerBundle\BigyouthImageResizerBundle() to config/bundles.php (Symfony 5+) or AppKernel.php (older versions).

  3. Enable Routing Add the routing in config/routes.yaml (Symfony 5+):

    bigyouth_image_resizer:
        resource: "@BigyouthImageResizerBundle/Controller/"
        type: annotation
    

    For Symfony <5, use app/config/routing.yml as shown in the README.

  4. First Use Case: Dynamic Resizing in a Controller Inject the Bigyouth\BigyouthImageResizerBundle\Service\ImageResizer service and call it with a source path, width, height, and optional format:

    use Bigyouth\BigyouthImageResizerBundle\Service\ImageResizer;
    
    public function resizeImage(ImageResizer $resizer)
    {
        $resizedPath = $resizer->resize(
            'path/to/source.jpg',
            300, // width
            200, // height
            'jpg' // optional format
        );
        return new Response("Resized image saved to: $resizedPath");
    }
    

Implementation Patterns

Common Workflows

  1. Dynamic Thumbnails in Views Use the service in a Twig template via a controller method:

    // Controller
    public function showProduct(Product $product, ImageResizer $resizer)
    {
        $thumbnail = $resizer->resize(
            $product->getImagePath(),
            150,
            150,
            'webp'
        );
        return $this->render('product/show.html.twig', ['thumbnail' => $thumbnail]);
    }
    

    In Twig:

    <img src="{{ thumbnail }}" alt="Product">
    
  2. Batch Processing Loop through files in a directory and resize them:

    public function batchResize(ImageResizer $resizer)
    {
        $files = glob('uploads/originals/*.jpg');
        foreach ($files as $file) {
            $resizer->resize($file, 800, 600, 'jpg');
        }
    }
    
  3. Integration with Form Uploads Resize uploaded files immediately after validation:

    public function upload(Request $request, ImageResizer $resizer)
    {
        $file = $request->file('image');
        $path = $file->store('uploads');
        $resizedPath = $resizer->resize(
            $path,
            1024,
            768,
            'jpg'
        );
        // Save $resizedPath to database
    }
    
  4. Custom Filter Sets Extend LiipImagineBundle filter sets for advanced resizing (e.g., adding watermarks):

    # config/packages/liip_imagine.yaml
    liip_imagine:
        filter_sets:
            watermarked:
                quality: 80
                filters:
                    thumbnail: { size: [400, 300], mode: outbound }
                    watermark: { image: assets/watermark.png, opacity: 70 }
    

    Then pass the filter set name to the resizer:

    $resizer->resize($path, 400, 300, 'jpg', 'watermarked');
    

Gotchas and Tips

Pitfalls

  1. Missing LiipImagineBundle Configuration

    • Error: No filter set found or blank images.
    • Fix: Ensure liip_imagine is configured with a default filter set (even if empty) and the imagine binary is installed (imagine PHP extension or gmagick/imagick).
    • Debug: Run php bin/console debug:config liip_imagine to verify settings.
  2. File Path Issues

    • Error: File not found or resized images saved to incorrect paths.
    • Fix: Use absolute paths (e.g., public/uploads/image.jpg) or ensure the working directory is correct. For Symfony 5+, use public_path() helper:
      $resizer->resize(public_path('uploads/image.jpg'), 300, 200);
      
  3. Deprecated Symfony Syntax

    • Issue: The bundle was last updated in 2019 and may not support Symfony 5+ features (e.g., autowiring, new config structure).
    • Workaround: Manually register the service in config/services.yaml:
      services:
          Bigyouth\BigyouthImageResizerBundle\Service\ImageResizer:
              arguments:
                  $liipImagineManager: '@liip_imagine.manager'
      
  4. Memory Limits

    • Error: Large images may exceed PHP’s memory_limit.
    • Fix: Increase memory_limit in php.ini or resize images in chunks using LiipImagineBundle's streaming filters.

Debugging Tips

  1. Log Resizer Output Temporarily add logging to the ImageResizer service to debug paths and parameters:

    use Psr\Log\LoggerInterface;
    
    public function resize($path, $width, $height, $format = null, $filter = 'default', LoggerInterface $logger)
    {
        $logger->info('Resizing', [
            'path' => $path,
            'width' => $width,
            'height' => $height,
            'filter' => $filter,
        ]);
        // ... rest of the method
    }
    
  2. Verify Filter Sets Check if the filter set exists and is correctly configured:

    php bin/console debug:config liip_imagine | grep filter_sets
    
  3. Test with Known Images Use a small, simple image (e.g., test.jpg) to isolate issues:

    $resizer->resize(__DIR__.'/test.jpg', 100, 100);
    

Extension Points

  1. Custom Storage Override the save() method in the ImageResizer service to write resized images to a custom location (e.g., S3):

    public function resize($path, $width, $height, $format = null, $filter = 'default')
    {
        $resizedPath = $this->manager->getBrowserPath($path, $filter, ['width' => $width, 'height' => $height]);
        $this->manager->resize($path, $resizedPath, $filter, ['width' => $width, 'height' => $height]);
        // Custom logic here (e.g., upload to S3)
        return $resizedPath;
    }
    
  2. Add Metadata Extend the service to include EXIF data or generate filenames with hashes:

    public function resize($path, $width, $height, $format = null, $filter = 'default')
    {
        $resizedPath = $this->manager->getBrowserPath($path, $filter, ['width' => $width, 'height' => $height]);
        $filename = pathinfo($resizedPath, PATHINFO_FILENAME) . '_' . md5($path) . '.' . $format;
        $this->manager->resize($path, $resizedPath, $filter, ['width' => $width, 'height' => $height]);
        return str_replace(pathinfo($resizedPath, PATHINFO_BASENAME), $filename, $resizedPath);
    }
    
  3. Event Listeners Trigger events before/after resizing (e.g., update database records):

    // config/services.yaml
    services:
        App\EventListener\ImageResizeListener:
            tags:
                - { name: kernel.event_listener, event: bigyouth.image_resizer.resize, method: onResize }
    
    // src/EventListener/ImageResizeListener.php
    public function onResize(ImageResizeEvent $event)
    {
        // $event->getSourcePath(), $event->getResizedPath()
    }
    

    Dispatch the event in the ImageResizer service after resizing.

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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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