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

contao/image

Contao Image is a PHP library for generating and manipulating images for Contao projects. It provides helpers for resizing, cropping, and creating responsive image variants, integrating with Contao’s image pipeline to deliver optimized outputs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require contao/image
    

    Ensure your project has PHP 8.1+ and a supported Laravel version (8.x+).

  2. Basic Usage

    use Contao\Image\Image;
    
    $image = new Image('path/to/image.jpg');
    $image->resize(300, 200); // Resize with width/height
    $image->save('path/to/output.jpg');
    
  3. First Use Case Dynamically generate thumbnails for uploaded files in a Laravel storage system:

    use Contao\Image\Image;
    use Illuminate\Support\Facades\Storage;
    
    $file = request()->file('image');
    $path = $file->store('uploads');
    
    $image = new Image(storage_path('app/' . $path));
    $image->resize(200, 200)->crop('center')->save(storage_path('app/thumbs/' . $path));
    

Where to Look First

  • Documentation: Contao Image Library Docs (if available) or inspect src/Contao/Image/Image.php for core methods.
  • Examples: Check the tests/ directory in the package for usage patterns.
  • Laravel Integration: Review vendor/contao/image/README.md for Laravel-specific notes.

Implementation Patterns

Core Workflows

  1. Dynamic Image Processing

    // In a Laravel controller or service
    public function processImage(Request $request) {
        $image = new Image($request->file('image')->path());
        $image->resize(800, 600)->quality(85)->save(storage_path('processed/' . $request->file('image')->hashName()));
        return response()->json(['success' => true]);
    }
    
  2. Batch Processing

    use Contao\Image\Image;
    use Illuminate\Support\Facades\Storage;
    
    $files = Storage::files('uploads');
    foreach ($files as $file) {
        $image = new Image(storage_path('app/' . $file));
        $image->resize(400, 400)->save(storage_path('app/thumbs/' . $file));
    }
    
  3. Integration with Laravel Filesystem

    // Custom Filesystem Adapter for Contao Image
    Storage::extend('contao', function ($app) {
        return new ContaoImageAdapter($app['files'], $app['config']);
    });
    
    // Usage:
    Storage::disk('contao')->put('image.jpg', $image->getData());
    

Laravel-Specific Patterns

  1. Service Provider Binding

    // In AppServiceProvider
    public function register() {
        $this->app->bind(Image::class, function ($app) {
            return new Image($app['path.storage'] . '/app/uploads/image.jpg');
        });
    }
    
  2. Middleware for Image Processing

    public function handle($request, Closure $next) {
        if ($request->hasFile('image')) {
            $image = new Image($request->file('image')->path());
            $image->resize(1024, 768)->save(storage_path('temp/' . $request->file('image')->hashName()));
        }
        return $next($request);
    }
    
  3. Eloquent Model Observers

    // In UserObserver
    public function saved(User $user) {
        if ($user->profile_image) {
            $image = new Image(storage_path('app/' . $user->profile_image));
            $image->resize(300, 300)->save(storage_path('app/thumbs/' . $user->profile_image));
        }
    }
    
  4. Queue Jobs for Async Processing

    // ProcessImageJob.php
    public function handle() {
        $image = new Image(storage_path('app/uploads/' . $this->file));
        $image->resize(1200, 800)->save(storage_path('app/processed/' . $this->file));
    }
    
    // Dispatch
    ProcessImageJob::dispatch($file->hashName());
    

Gotchas and Tips

Pitfalls

  1. Memory Limits

    • Large images may exceed PHP’s memory_limit. Use ->optimize() or chunk processing for big files.
    • Fix: Increase memory_limit in php.ini or process images in smaller batches.
  2. File Path Handling

    • Contao’s Image class expects absolute paths. Relative paths may fail silently.
    • Fix: Always use storage_path() or public_path():
      $image = new Image(storage_path('app/uploads/' . $file));
      
  3. GD vs. Imagick

    • The package defaults to GD. If Imagick is installed, it may override settings.
    • Fix: Explicitly set the driver:
      Image::setDriver('gd'); // or 'imagick'
      
  4. Case Sensitivity

    • File extensions (e.g., .JPG vs .jpg) may cause issues on case-sensitive systems.
    • Fix: Normalize extensions:
      $path = strtolower($path);
      
  5. Permission Issues

    • Writing to directories (e.g., storage/app/thumbs) requires proper permissions.
    • Fix: Run chmod -R 775 storage/ or use Laravel’s storage:link.

Debugging Tips

  1. Check Supported Formats

    if (!Image::isSupported('path/to/image.webp')) {
        throw new \Exception('Unsupported format');
    }
    
  2. Log Errors

    try {
        $image->resize(1000, 1000);
    } catch (\Exception $e) {
        \Log::error('Image processing failed: ' . $e->getMessage());
    }
    
  3. Verify Image Data

    $image = new Image('path/to/image.jpg');
    \Log::info([
        'width' => $image->getWidth(),
        'height' => $image->getHeight(),
        'mime' => $image->getMimeType(),
    ]);
    

Extension Points

  1. Custom Filters Create a decorator for Image:

    class CustomImage extends Image {
        public function applyCustomFilter() {
            $this->applyFilter('some_custom_filter');
        }
    }
    
  2. Laravel Facade Add a facade for convenience:

    // In config/app.php
    'aliases' => [
        'Image' => Contao\Facades\Image::class,
    ];
    
    // Usage:
    Image::make('path')->resize(500, 500);
    
  3. Blade Directives

    // In AppServiceProvider
    Blade::directive('image', function ($expression) {
        return "<?php echo (new \\Contao\\Image\\Image({$expression}))->resize(200, 200)->toHtml(); ?>";
    });
    
    // Usage in Blade:
    <img src="{{ image('path/to/image.jpg') }}">
    
  4. Cache Busting Append a hash to processed images to bypass cache:

    $hash = md5_file($image->getPath());
    $image->save(storage_path("app/thumbs/{$hash}_{$file}"));
    

Performance Tips

  1. Reuse Instances Avoid recreating Image objects for the same file:

    static $cache = [];
    $image = $cache[$path] ?? new Image($path);
    
  2. Lazy Loading Process images only when needed (e.g., in a view):

    $imagePath = storage_path('app/uploads/' . $file);
    $image = new Image($imagePath);
    if ($shouldResize) {
        $image->resize(600, 400);
    }
    
  3. Use ->getData() for In-Memory Processing Avoid saving intermediate files:

    $data = $image->resize(100, 100)->getData();
    Storage::disk('s3')->put('thumb.jpg', $data);
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor