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

pixelandtonic/imagine

Imagine is a Laravel package that streamlines image handling and transformations using the Imagine library. Generate thumbnails, crop, resize, and apply filters with a clean API for integrating image processing into your app’s workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require pixelandtonic/imagine
    

    Add the service provider to config/app.php under providers:

    Pixelandtonic\Imagine\ImagineServiceProvider::class,
    
  2. Basic Usage Initialize the service in a controller or service class:

    use Pixelandtonic\Imagine\Imagine;
    
    public function __construct(Imagine $imagine)
    {
        $this->imagine = $imagine;
    }
    
  3. First Use Case: Resizing an Image

    $image = $this->imagine->open(public_path('images/original.jpg'));
    $image->resize(300, 200); // Width, height
    $image->save(public_path('images/resized.jpg'));
    
  4. Configuration Check config/imagine.php for default settings (e.g., GD, Imagick, or Gmagick drivers). Set your preferred driver:

    'driver' => 'imagick', // or 'gd', 'gmagick'
    

Implementation Patterns

Common Workflows

1. Dynamic Image Processing in Controllers

public function processImage(Request $request)
{
    $image = $this->imagine->open($request->file('image')->path());
    $image->resize(800, null, function ($constraint) {
        $constraint->aspectRatio();
        $constraint->upscale();
    });
    $image->save(public_path('uploads/' . $request->file('image')->hashName()));
}

2. Reusable Image Manipulation Service

Create a dedicated service class:

namespace App\Services;

use Pixelandtonic\Imagine\Imagine;

class ImageService {
    protected $imagine;

    public function __construct(Imagine $imagine)
    {
        $this->imagine = $imagine;
    }

    public function generateThumbnail($path, $width, $height)
    {
        $image = $this->imagine->open($path);
        $image->resize($width, $height);
        return $image->getImage();
    }
}

3. Batch Processing with Queues

Use Laravel queues to handle heavy processing:

use App\Jobs\ProcessImageJob;

ProcessImageJob::dispatch($imagePath, $newDimensions);

Job class:

public function handle()
{
    $image = $this->imagine->open($this->imagePath);
    $image->resize($this->width, $this->height);
    $image->save(public_path('processed/' . $this->imagePath));
}

4. Integration with Storage Facades

Use Laravel’s storage system for flexibility:

use Illuminate\Support\Facades\Storage;

$image = $this->imagine->open(Storage::path('images/original.jpg'));
$image->resize(400, 400);
$image->save(Storage::path('images/thumbnail.jpg'));

Integration Tips

1. Middleware for Image Processing

Create middleware to auto-process images on upload:

public function handle($request, Closure $next)
{
    if ($request->hasFile('image')) {
        $image = $this->imagine->open($request->file('image')->path());
        $image->resize(1024, 1024);
        $image->save($request->file('image')->path());
    }
    return $next($request);
}

2. Laravel Filesystem Events

Listen to filesystem events to process images post-upload:

Storage::disk('public')->addListener('after', function ($event) {
    if ($event->path()->endsWith('.jpg') || $event->path()->endsWith('.png')) {
        $image = $this->imagine->open(storage_path('app/' . $event->path()));
        $image->resize(600, 600);
        $image->save(storage_path('app/thumbs/' . $event->path()));
    }
});

3. Caching Processed Images

Use Laravel’s cache to avoid reprocessing:

$cacheKey = 'thumbnail_' . md5($originalPath);
$thumbnailPath = Cache::remember($cacheKey, now()->addDays(7), function () use ($originalPath) {
    $image = $this->imagine->open($originalPath);
    $image->resize(200, 200);
    return $image->save(public_path('thumbs/' . basename($originalPath)));
});

Gotchas and Tips

Pitfalls

1. Driver Compatibility Issues

  • GD vs. Imagick: GD is slower but widely available; Imagick offers more features but requires installation.
  • Debugging: If images fail to process, check if the driver is installed:
    php -m | grep -E 'gd|imagick'
    
  • Fix: Ensure the driver is enabled in php.ini and restart the server.

2. Memory Limits

  • Large images may hit PHP’s memory_limit. Increase it temporarily:
    ini_set('memory_limit', '512M');
    
  • Tip: Process images in chunks or use Imagick’s memory-efficient methods.

3. File Permissions

  • Ensure the storage directory is writable:
    chmod -R 775 storage/app/public
    

4. Aspect Ratio Distortion

  • Always use constraints to maintain aspect ratio:
    $image->resize(300, 300, function ($constraint) {
        $constraint->aspectRatio(); // Preserve aspect ratio
    });
    

Debugging Tips

1. Log Image Metadata

Inspect image properties before/after processing:

$image = $this->imagine->open($path);
\Log::info('Original dimensions:', [
    'width' => $image->getSize()->getWidth(),
    'height' => $image->getSize()->getHeight(),
]);

2. Check for Corrupted Images

Use try-catch to handle invalid files:

try {
    $image = $this->imagine->open($path);
} catch (\ImagickException $e) {
    \Log::error('Failed to open image: ' . $e->getMessage());
}

3. Verify Save Paths

Ensure paths are correct and directories exist:

$directory = dirname(public_path('images/processed.jpg'));
if (!file_exists($directory)) {
    mkdir($directory, 0777, true);
}

Extension Points

1. Custom Filters

Extend the library by creating custom filters:

namespace App\Filters;

use Pixelandtonic\Imagine\Filters\FilterInterface;

class RoundedCornersFilter implements FilterInterface {
    public function apply($image)
    {
        $image->resizeCanvas(300, 300, 'white');
        $image->draw()->rectangle(
            0, 0, 300, 300,
            function ($draw) {
                $draw->stroke('#000');
                $draw->radius(20);
            }
        );
        return $image;
    }
}

Register the filter in ImagineServiceProvider:

$this->app->bind('app.filters.rounded-corners', function () {
    return new \App\Filters\RoundedCornersFilter();
});

2. Dynamic Driver Selection

Override the default driver in runtime:

$imagine = new Imagine();
$imagine->use(\Imagine\Gd\Imagine::class); // Switch to GD

3. Event Listeners for Image Processing

Dispatch events before/after processing:

event(new ImageProcessingEvent($image, 'resize'));

Listen to the event in an observer:

public function handle(ImageProcessingEvent $event)
{
    \Log::info('Processing image: ' . $event->operation);
}

4. Laravel Mix Integration

Process images during asset compilation:

mix.js('app.js', 'public/js')
    .then(() => {
        const { Imagine } = require('pixelandtonic/imagine');
        const imagine = new Imagine();
        // Process images programmatically
    });
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.
terminal42/code-quality-tools
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