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

Imagine Bundle Laravel Package

liip/imagine-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require liip/imagine-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Liip\ImagineBundle\LiipImagineBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration: Create config/packages/liip_imagine.yaml:

    liip_imagine:
        driver: 'gd' # or 'gmagick'/'imagick'
        filter_sets:
            my_thumbnail:
                filters:
                    thumbnail: { size: [100, 100], mode: outbound }
    
  3. First Use Case: Generate a thumbnail in a controller:

    use Liip\ImagineBundle\Imagine\Filter\FilterConfiguration;
    use Liip\ImagineBundle\Service\FilterService;
    
    public function show(Image $image, FilterService $filterService)
    {
        $path = $filterService->getPath($image->getPath(), 'my_thumbnail');
        return new Response(file_get_contents($path));
    }
    

Key Files to Review

  • config/packages/liip_imagine.yaml (default config)
  • src/Controller/ImageController.php (example usage)
  • templates/imagine/filters.html.twig (Twig integration)

Implementation Patterns

Common Workflows

1. Dynamic Filter Sets

Define reusable filter sets in YAML:

liip_imagine:
    filter_sets:
        social_share:
            filters:
                thumbnail: { size: [600, 300], mode: outbound }
                background: { color: '#ffffff' }
                watermark: { image: '%kernel.project_dir%/public/images/watermark.png', opacity: 0.2 }

Apply in controller:

$path = $filterService->getPath($originalPath, 'social_share');

2. On-the-Fly Filtering

Chain filters dynamically:

$filterManager = $this->get('liip_imagine.filter.manager');
$filterConfig = new FilterConfiguration();
$filterConfig->add($filterManager->findFilter('thumbnail'), ['size' => [200, 200]]);
$filterConfig->add($filterManager->findFilter('watermark'), ['image' => $watermarkPath]);

$path = $filterService->getPath($originalPath, null, $filterConfig);

3. Twig Integration

Use in templates:

<img src="{{ asset(liip_imagine_filter(image.path, 'my_thumbnail')) }}">

4. Cache Management

Clear cache for a filter set:

php bin/console liip:imagine:cache:remove my_thumbnail

Or programmatically:

$this->get('liip_imagine.cache.manager')->remove($filterSetName);

5. Event Listeners

Trigger actions post-filtering:

// config/services.yaml
App\EventListener\ImageFilterListener:
    tags:
        - { name: kernel.event_listener, event: liip_imagine.filter.post, method: onPostFilter }

Integration Tips

Symfony Forms

Use with EntityType for file uploads:

$builder->add('image', EntityType::class, [
    'class' => Image::class,
    'mapped' => false,
    'label' => 'Upload Image',
]);

API Responses

Return filtered images as StreamedResponse:

public function getFilteredImage(Image $image, FilterService $filterService)
{
    $path = $filterService->getPath($image->getPath(), 'my_thumbnail');
    return new StreamedResponse(function () use ($path) {
        echo file_get_contents($path);
    }, 200, ['Content-Type' => 'image/jpeg']);
}

Doctrine Entities

Store filtered paths in DB:

/**
 * @ORM\Column(type="string", nullable=true)
 */
private $thumbnailPath;

Gotchas and Tips

Pitfalls

1. Driver Compatibility

  • GD vs. Imagick/Gmagick:
    • GD is slower but widely available; Imagick/Gmagick offer advanced features.
    • Test locally before deploying to shared hosting (GD is often preinstalled).
  • Fallback: Configure a fallback driver in liip_imagine.yaml:
    driver: gd
    fallback_driver: imagick
    

2. Cache Invalidation

  • Manual Clearing: Forgetting to clear cache after changing filter sets:
    php bin/console cache:clear
    php bin/console liip:imagine:cache:remove my_thumbnail
    
  • Automatic Invalidation: Use liip_imagine.cache.invalidator service to hook into events (e.g., file uploads).

3. File Permissions

  • Ensure var/cache/liip_imagine is writable:
    chmod -R 775 var/cache/liip_imagine
    

4. Memory Limits

  • Large images may hit PHP’s memory_limit. Adjust in php.ini or use smaller filter sets.
  • Workaround: Process images in chunks or use imagick for better memory handling.

5. Filter Order Matters

  • Filters execute in declaration order. Example:
    filters:
        resize: { width: 800 }  # Runs first
        thumbnail: { size: [200, 200] }  # Runs second (overrides resize)
    

Debugging Tips

1. Log Filter Output

Enable debug mode and check var/log/dev.log for filter execution logs.

2. Validate Filter Sets

Use the liip:imagine:filter:list command to verify configured filter sets:

php bin/console liip:imagine:filter:list

3. Test Locally with imagick

Simulate production environments:

# config/packages/dev/liip_imagine.yaml
driver: imagick

4. Check File Paths

Ensure source and cache paths are correct in liip_imagine.yaml:

source: '%kernel.project_dir%/public/uploads'
cache: '%kernel.project_dir%/var/cache/liip_imagine'

Extension Points

1. Custom Filters

Create a custom filter (e.g., RoundCornersFilter):

namespace App\Imagine\Filter;

use Liip\ImagineBundle\Imagine\Filter\FilterInterface;

class RoundCornersFilter implements FilterInterface
{
    public function applyFilter($image)
    {
        // Use Imagine library to add rounded corners
        return $image->effects()->gaussianBlur(0.5);
    }
}

Register in config/services.yaml:

App\Imagine\Filter\RoundCornersFilter:
    tags:
        - { name: liip_imagine.filter, alias: round_corners }

2. Dynamic Filter Sets via API

Fetch filter sets from a database:

$filterConfig = new FilterConfiguration();
$dbFilterSet = $this->getFilterSetFromDB($filterSetName);
foreach ($dbFilterSet['filters'] as $filter => $options) {
    $filterConfig->add($filterManager->findFilter($filter), $options);
}

3. Event-Driven Workflows

Listen for liip_imagine.filter.pre and liip_imagine.filter.post events:

public function onPreFilter(GetResponseForFilterEvent $event)
{
    if (!$event->isValid()) {
        $event->setValid(false);
        // Custom logic (e.g., skip if image is already optimized)
    }
}

4. Cloud Storage Integration

Use liip_imagine.cache.manager to store filtered images in S3:

$cacheManager = $this->get('liip_imagine.cache.manager');
$cacheManager->setCacheDir('s3://my-bucket/cache/');

5. WebP Conversion

Add a filter set for WebP:

liip_imagine:
    filter_sets:
        webp_conversion:
            filters:
                convert: { format: webp, quality: 80 }
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware