Weave 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

gregwar/image

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require gregwar/image
    

    Add to composer.json if not using autoloading:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Gregwar\\Image\\": "vendor/gregwar/image/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case Load and resize an image:

    use Gregwar\Image\Image;
    
    $image = Image::open('path/to/image.jpg');
    $image->resize(300, 200); // Width, height
    $image->save('path/to/resized.jpg');
    
  3. Key Classes

    • Gregwar\Image\Image: Core class for image manipulation.
    • Gregwar\Image\Geometry\Size: For width/height calculations.
    • Gregwar\Image\Geometry\Point: For positioning (e.g., watermarks).
  4. Where to Look First

    • Documentation (if available; check for README or Wiki).
    • src/Gregwar/Image/Image.php for core methods.
    • tests/ for usage examples and edge cases.

Implementation Patterns

Common Workflows

  1. Dynamic Thumbnails

    $image = Image::open($request->file('image')->getRealPath());
    $image->resize(800, 600, ['mode' => 'outbound']);
    $image->save(storage_path("app/thumbs/{$request->id}.jpg"));
    
    • Use 'mode' => 'outbound' to maintain aspect ratio with padding.
  2. Watermarking

    $watermark = Image::open(public_path('watermark.png'));
    $image->stamp($watermark, 10, 10, 0.5); // Position, opacity
    
  3. Batch Processing

    $files = Storage::disk('s3')->files('originals/');
    foreach ($files as $file) {
        $image = Image::open(storage_path("app/{$file}"));
        $image->resize(1200, 800);
        $image->save(storage_path("app/thumbs/{$file}"));
    }
    
  4. Integration with Laravel Filesystem

    $stream = fopen($request->file('image')->getRealPath(), 'r+');
    $image = Image::open($stream);
    // Process...
    $image->saveToStream($stream);
    $stream->seek(0);
    return response()->stream(fn() => $stream, 200, ['Content-Type' => 'image/jpeg']);
    

Best Practices

  • Error Handling: Wrap operations in try-catch for Gregwar\Image\Exception.
    try {
        $image->resize(100, 100);
    } catch (\Gregwar\Image\Exception $e) {
        Log::error("Image resize failed: {$e->getMessage()}");
    }
    
  • Memory Management: Use save() instead of saveToStream() for large files to avoid memory spikes.
  • Fallbacks: Validate image types before processing:
    if (!in_array($request->file('image')->getClientMimeType(), ['image/jpeg', 'image/png'])) {
        throw new \InvalidArgumentException('Unsupported image type.');
    }
    

Laravel-Specific Tips

  • Service Provider: Register a facade for cleaner syntax:

    // app/Providers/AppServiceProvider.php
    use Gregwar\Image\Facades\Image as ImageFacade;
    
    public function boot()
    {
        app()->bind('image', function () {
            return new ImageFacade();
        });
    }
    

    Now use Image::open() directly in controllers/views.

  • Middleware for Validation:

    public function handle($request, Closure $next)
    {
        if ($request->hasFile('image')) {
            $image = Image::open($request->file('image')->getRealPath());
            if ($image->width > 2000 || $image->height > 2000) {
                abort(422, 'Image too large.');
            }
        }
        return $next($request);
    }
    

Gotchas and Tips

Pitfalls

  1. GD vs. Imagick

    • The package defaults to GD. For advanced features (e.g., transparency layers), ensure imagick is installed:
      pecl install imagick
      
    • Force Imagick in config:
      $image = Image::open('file.jpg', ['driver' => 'imagick']);
      
  2. Memory Limits

    • Large images may hit PHP’s memory_limit. Increase it temporarily:
      ini_set('memory_limit', '512M');
      
    • Use save() with a temporary file path to avoid loading the entire image into memory.
  3. File Permissions

    • Ensure the target directory for saved images is writable:
      chmod -R 755 storage/app/thumbs
      
  4. Aspect Ratio Distortion

    • Resizing without constraints distorts images. Always specify a mode:
      $image->resize(300, 200, ['mode' => 'aspect']); // Maintains ratio
      

Debugging

  • Check Supported Formats:
    $image = Image::open('file.unknown');
    if (!$image) {
        throw new \RuntimeException('Unsupported image format.');
    }
    
  • Log Errors:
    try {
        $image->resize(100, 100);
    } catch (\Gregwar\Image\Exception $e) {
        Log::debug("Image error: " . $e->getMessage(), ['file' => 'image.jpg']);
    }
    

Extension Points

  1. Custom Drivers Override the default driver (GD/Imagick) by extending Gregwar\Image\Driver\AbstractDriver.

  2. Filters Create reusable filters:

    class SharpenFilter {
        public static function apply(Image $image) {
            $image->sharpen(50);
        }
    }
    
  3. Event Listeners Trigger actions post-processing:

    $image->on('save', function () {
        // Log or notify after save
    });
    

Config Quirks

  • Default Driver: Set in config/gregwar-image.php (if available) or via:
    Image::setDriver('imagick');
    
  • Quality Settings: Adjust JPEG/PNG quality globally:
    Image::setDefaultQuality(85); // 0-100
    

Performance

  • Cache Geometry: Avoid recalculating dimensions:
    $width = $image->width; // Cache this if reused
    
  • Stream Processing: For large files, use streams to avoid memory issues:
    $stream = fopen('large_image.jpg', 'r+');
    $image = Image::open($stream);
    $image->resize(1000, 1000);
    $image->saveToStream($stream);
    fclose($stream);
    
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.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums