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

Gregwar Image Bundle Laravel Package

arkounay/gregwar-image-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require arkounay/gregwar-image-bundle
    

    Ensure ext-gd is enabled in your PHP environment.

  2. Configuration Add the bundle to config/bundles.php (Symfony 5+):

    return [
        // ...
        Arkounay\GregwarImageBundle\ArkounayGregwarImageBundle::class => ['all' => true],
    ];
    

    Configure config/packages/gregwar_image.yaml:

    gregwar_image:
        web_dir: '%kernel.project_dir%/public'
        cache_dir: '%kernel.project_dir%/var/cache/gregwar_image'
    
  3. First Use Case Generate a thumbnail in a controller:

    use Arkounay\GregwarImageBundle\Service\ImageService;
    
    public function thumbnail(ImageService $imageService)
    {
        $image = $imageService->get('path/to/image.jpg');
        $image->resize(100, 100);
        $image->save('path/to/thumbnail.jpg');
        return new Response('Thumbnail generated!');
    }
    
  4. Twig Integration Use the image Twig filter in templates:

    <img src="{{ asset(image('path/to/image.jpg')->resize(200, 200)->getUrl()) }}">
    

Implementation Patterns

Core Workflows

  1. Image Processing Pipeline Chain methods for transformations:

    $image = $imageService->get('image.jpg')
        ->resize(800, 600)
        ->crop(200, 200, 100, 100) // x, y, width, height
        ->rotate(90)
        ->watermark('watermark.png', 0.5, 0.5)
        ->save('processed.jpg');
    
  2. Dynamic URL Generation Generate URLs with query parameters for caching:

    $url = $imageService->get('image.jpg')
        ->resize(300, 300)
        ->getUrl(); // e.g., /cache/abc123.jpg?width=300&height=300
    
  3. Batch Processing Process multiple images in a loop:

    foreach ($imagePaths as $path) {
        $image = $imageService->get($path)
            ->resize(400, 400)
            ->save("thumbs/{$path}");
    }
    

Integration Tips

  1. Symfony Forms Use with VichUploaderBundle for file uploads:

    // In a form type
    $builder->add('image', FileType::class, [
        'mapped' => false,
        'constraints' => [new Image(['maxSize' => '1024k'])]
    ]);
    
  2. API Responses Return processed images as binary responses:

    $image = $imageService->get('image.jpg')->resize(500, 500);
    return new BinaryFileResponse($image->getPath(), 200, [
        'Content-Type' => $image->getMimeType(),
        'Content-Disposition' => 'inline; filename="image.jpg"',
    ]);
    
  3. Event Listeners Trigger processing on upload:

    // src/EventListener/ImageUploadListener.php
    public function onUpload(UploadEvent $event)
    {
        $image = $this->imageService->get($event->getPath());
        $image->resize(800, 600)->save($event->getPath());
    }
    
  4. Twig Extensions Create custom filters/extensions:

    // src/Twig/ImageExtension.php
    public function getThumbnailUrl($path, $width, $height)
    {
        return $this->imageService->get($path)
            ->resize($width, $height)
            ->getUrl();
    }
    

Gotchas and Tips

Common Pitfalls

  1. GD Extension Requirements

    • Ensure ext-gd is installed and enabled (php -m | grep gd).
    • For advanced features (e.g., PNG transparency), verify GD version supports it.
  2. Cache Directory Permissions

    • Set cache_dir permissions to 775 or 777 if PHP runs as a non-root user:
      chmod -R 775 %kernel.project_dir%/var/cache/gregwar_image
      
  3. Memory Limits

    • Large images may hit PHP’s memory_limit. Increase if needed:
      # config/packages/framework.yaml
      framework:
          php_errors:
              memory_limit: 512M
      
  4. URL Generation Quirks

    • Hardcoded web_dir in URLs? Override the getUrl() method or use a custom service:
      $image->setWebDir('/custom/web/path');
      
  5. Mime Type Detection

    • Incorrect MIME types may cause issues. Force MIME type if needed:
      $image->setMimeType('image/jpeg');
      

Debugging Tips

  1. Log Image Metadata Dump image properties for debugging:

    $image = $imageService->get('image.jpg');
    \Log::debug([
        'width' => $image->getWidth(),
        'height' => $image->getHeight(),
        'mime' => $image->getMimeType(),
        'path' => $image->getPath(),
    ]);
    
  2. Check Cache Directory Verify processed images are saved to cache_dir:

    ls -la %kernel.project_dir%/var/cache/gregwar_image
    
  3. Validate Config Ensure web_dir and cache_dir paths are correct and writable. Test with:

    $this->imageService->getConfig()->getWebDir();
    

Extension Points

  1. Custom Filters Extend the Gregwar\Image\Image class:

    // src/Service/CustomImage.php
    class CustomImage extends \Gregwar\Image\Image
    {
        public function customFilter()
        {
            // Custom logic
        }
    }
    

    Register as a service and replace the default.

  2. Override Templates Customize Twig templates (e.g., image.html.twig) in templates/bundles/gregwarimage/.

  3. Add New Operations Extend the ImageService to support custom operations:

    // src/Service/ExtendedImageService.php
    public function addBorder($color, $width)
    {
        $this->image->drawRectangle(
            0, 0, $this->image->getWidth(), $this->image->getHeight(),
            $color, $width
        );
        return $this;
    }
    
  4. Event Dispatching Listen for image events (e.g., ImageEvent):

    // config/services.yaml
    services:
        App\EventListener\ImageListener:
            tags:
                - { name: kernel.event_listener, event: gregwar_image.process, method: onProcess }
    

Performance Tips

  1. Cache Aggressively Use query parameters for cache busting:

    <img src="{{ asset(image('image.jpg')->resize(300, 300)->getUrl()) }}">
    

    Avoid regenerating images unless parameters change.

  2. Lazy Loading Process images on-demand (e.g., in a Controller or Command) rather than during request handling.

  3. Batch Processing Use Symfony’s Messenger component for async processing:

    $this->messageBus->dispatch(new ProcessImageMessage($imagePath, $transformations));
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime