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

Simpleimage Laravel Package

claviska/simpleimage

SimpleImage is a lightweight PHP 8+ GD image manipulation class. Load images from files/strings/URIs, auto-orient via EXIF, resize/crop/overlay/watermark, draw shapes/text, apply filters, and convert between GIF/JPEG/PNG/WEBP/BMP/AVIF. Chainable, exception-based.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require claviska/simpleimage
    

    No additional configuration is required—just autoload.

  2. First Use Case: Basic Image Resizing Load an image and resize it in a single line:

    use SimpleImage\SimpleImage;
    
    $image = new SimpleImage('/path/to/image.jpg');
    $image->resize(300, 200)->save('/path/to/resized.jpg');
    
  3. Where to Look First

    • Documentation: GitHub README (if available) or inline PHPDoc comments.
    • Core Methods: Focus on resize(), crop(), save(), output(), and webp() (for modern formats).
    • Examples: Check the tests/ directory for real-world usage patterns.
    • Deprecation Note: The SimpleImage::reset() method is deprecated in v4.4.0 (replaced by PHP 8.5’s removal of imagedestroy()). Avoid using it.

Implementation Patterns

Common Workflows

  1. Dynamic Thumbnail Generation

    public function generateThumbnail($path, $width, $height)
    {
        $image = new SimpleImage($path);
        $image->resize($width, $height, SimpleImage::THUMBNAIL_PROPORTIONAL);
        return $image->save('/thumbs/' . basename($path));
    }
    
  2. Batch Processing with Laravel Filesystem Integrate with Laravel’s Storage facade for cloud storage (e.g., S3):

    use Illuminate\Support\Facades\Storage;
    
    $path = Storage::path('images/original.jpg');
    $image = new SimpleImage($path);
    $image->resize(800, 600)->save(Storage::disk('s3')->path('thumbs/resized.jpg'));
    
  3. Image Optimization Pipeline Chain methods for efficiency:

    $image
        ->resize(1200, 800, SimpleImage::THUMBNAIL_PROPORTIONAL)
        ->sharpen(10)
        ->save('/optimized.jpg');
    
  4. WebP Conversion for Performance

    $image = new SimpleImage('image.jpg');
    $image->webp()->save('image.webp'); // Auto-converts to WebP
    

Integration Tips

  • Laravel Service Provider: Bind the class to the container for dependency injection:

    $this->app->bind(SimpleImage::class, function () {
        return new SimpleImage();
    });
    

    Usage in controllers:

    public function __construct(private SimpleImage $image) {}
    
  • Queue Jobs for Heavy Processing: Offload image tasks to Laravel queues to avoid timeouts:

    dispatch(new ProcessImageJob($imagePath, $newDimensions));
    
  • Middleware for Image Validation: Validate uploaded images before processing:

    public function handle($request, Closure $next)
    {
        if ($request->hasFile('image')) {
            $image = new SimpleImage($request->file('image')->path());
            if (!$image->isValid()) {
                return redirect()->back()->withError('Invalid image');
            }
        }
        return $next($request);
    }
    

Gotchas and Tips

Pitfalls

  1. GD Library Requirements

    • Ensure php-gd is installed (sudo apt-get install php-gd on Ubuntu).
    • Check for errors like Call to undefined function gd_info() if missing.
  2. Memory Limits

    • Large images may hit PHP’s memory_limit. Increase it temporarily:
      ini_set('memory_limit', '512M');
      
    • Use SimpleImage::THUMBNAIL_PROPORTIONAL to avoid memory spikes.
  3. File Permissions

    • Ensure the output directory is writable:
      chmod -R 755 storage/app/public/thumbs
      
  4. Aspect Ratio Distortion

    • Always specify SimpleImage::THUMBNAIL_PROPORTIONAL or SimpleImage::THUMBNAIL_OUTBOUND to avoid stretched images:
      $image->resize(300, 200, SimpleImage::THUMBNAIL_PROPORTIONAL);
      
  5. Deprecated reset() Method

    • Avoid using SimpleImage::reset() in v4.4.0+ as it relies on deprecated imagedestroy().
    • Workaround: Manually close resources if needed (e.g., in custom extensions):
      $image->close(); // Hypothetical; verify if package provides alternative
      

Debugging

  • Check Image Validity:
    if (!$image->isValid()) {
        Log::error('Invalid image: ' . $image->getError());
    }
    
  • Log Errors: Enable GD error reporting:
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    

Extension Points

  1. Custom Filters Extend the class for domain-specific filters (e.g., watermarking):

    class WatermarkedImage extends SimpleImage
    {
        public function addWatermark($watermarkPath, $position = 'bottom-right')
        {
            // Implement using GD functions (ensure no `imagedestroy()` calls)
        }
    }
    
  2. Laravel Artisan Commands Create a command for bulk processing:

    Artisan::command('images:resize', function () {
        $images = Storage::files('images/originals');
        foreach ($images as $image) {
            $this->resizeImage($image);
        }
    });
    
  3. Event Listeners Trigger events after image processing:

    event(new ImageProcessed($imagePath, $newPath));
    

Pro Tips

  • Cache Processed Images: Use Laravel’s cache to avoid reprocessing:

    $cacheKey = "thumb_{$width}_{$height}_{$imagePath}";
    if (!Cache::has($cacheKey)) {
        $image->resize($width, $height)->save($cachedPath);
        Cache::put($cacheKey, true, now()->addYears(1));
    }
    
  • Laravel Blade Directives: Create a custom Blade directive for dynamic image tags:

    Blade::directive('thumb', function ($path) {
        return "<?php echo SimpleImage::thumb($path, 200, 200); ?>";
    });
    

    Usage:

    <img src="{{ thumb('image.jpg') }}">
    
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