askancy/laravel-smart-thumbnails

Advanced thumbnail generation with smart cropping for Laravel applications

Installs: 16

Dependents: 0

Suggesters: 0

Security: 0

Stars: 1

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/askancy/laravel-smart-thumbnails

2.0 2025-12-11 15:55 UTC

This package is auto-updated.

Last update: 2025-12-11 15:56:50 UTC


README

Laravel Smart Thumbnails Demo

The most advanced thumbnail generation package for Laravel with intelligent cropping, multi-disk support, subdirectory organization, and bulletproof error handling that never breaks your application.

Latest Version on Packagist Total Downloads Tests

✨ What's New in Latest Version

Major Improvements

  • πŸ–ΌοΈ AVIF Format Support - Next-generation image format with 50% smaller file sizes than JPEG
  • 🎯 Intervention Image 3.x Support - Full compatibility with the latest Intervention Image version
  • 🏷️ Smart Cache Tagging - Targeted cache invalidation without affecting your entire application cache
  • 🧩 Refactored Architecture - New ThumbnailGenerator utility class for better code reusability
  • 🧠 Enhanced Smart Crop - Improved rule-of-thirds algorithm with better image analysis
  • πŸ“ Complete PHPDoc - Full documentation for all public methods and classes

Performance & Reliability

  • ⚑ Faster Cache Operations - Consistent 1-hour TTL across all cache layers
  • 🎨 Better Memory Management - Automatic cleanup with Intervention Image 3.x
  • πŸ”§ No Breaking Changes - Fully backward compatible with existing implementations

πŸ“š See the Upgrade Guide for migration instructions πŸ“‹ See CHANGELOG.md for complete version history

πŸš€ Features

  • ✨ Smart Crop Algorithm - Based on dont-crop with energy detection
  • πŸ›‘οΈ Bulletproof Error Handling - Never breaks your application, always shows something
  • πŸ“ Subdirectory Organization - Handles millions of thumbnails with optimal filesystem performance
  • πŸ’Ύ Multi-Disk Support - S3, local, scoped disks, and custom storage solutions
  • 🎨 Multiple Variants - Responsive design with preset variants
  • πŸ–ΌοΈ Modern Formats - AVIF, WebP, JPEG, PNG support with optimal compression
  • πŸš€ Lazy Generation - Thumbnails created only when needed
  • πŸ”„ Intelligent Fallbacks - Original image β†’ Custom placeholder β†’ Generated placeholder
  • ⚑ High Performance - Optimized for large-scale applications
  • πŸ—‘οΈ Maintenance Commands - Purge, optimize, and analyze thumbnails
  • πŸ§ͺ Fully Tested - Comprehensive PHPUnit test suite

πŸ“‹ Requirements

  • PHP 8.1+
  • Laravel 10.0, 11.0, or 12.0
  • Intervention Image 3.9+
  • GD extension (required) or ImageMagick extension (recommended, required for AVIF format)
  • Redis or Memcached extension (optional, for cache tagging support)

πŸ“¦ Installation

Install via Composer:

composer require askancy/laravel-smart-thumbnails

Publish configuration:

php artisan vendor:publish --tag=laravel-smart-thumbnails-config

πŸ›‘οΈ Error-Safe Usage (Recommended)

The package offers bulletproof error handling that ensures your application never breaks due to missing images or storage issues.

Silent Mode (Never Fails)

{{-- βœ… NEVER throws exceptions, always shows something --}}
<img src="{{ Thumbnail::set('gallery')->src($photo->path, 's3')->urlSafe() }}" alt="Gallery">

{{-- βœ… Explicit silent mode --}}
<img src="{{ Thumbnail::silent()->set('products')->src($image, 's3')->url('thumb') }}" alt="Product">

Strict Mode (For Development/Admin)

{{-- ⚠️ May throw exceptions for debugging --}}
<img src="{{ Thumbnail::strict()->set('gallery')->src($photo->path, 's3')->url() }}" alt="Gallery">

{{-- ⚠️ Standard mode (configurable default) --}}
<img src="{{ Thumbnail::set('gallery')->src($photo->path, 's3')->url('large') }}" alt="Gallery">

🎯 Quick Examples

Responsive Blog Headers

<picture>
    <source media="(max-width: 640px)" 
            srcset="{{ Thumbnail::set('blog')->src($post->image, 's3')->urlSafe('card') }}">
    <source media="(min-width: 641px)" 
            srcset="{{ Thumbnail::set('blog')->src($post->image, 's3')->urlSafe('hero') }}">
    <img src="{{ Thumbnail::set('blog')->src($post->image, 's3')->urlSafe('hero') }}" 
         alt="{{ $post->title }}"
         loading="lazy">
</picture>

Homepage Slider (Never Breaks)

<div class="hero-slider">
    @foreach($slides as $slide)
        <div class="slide">
            {{-- This slider will NEVER break, even with missing images --}}
            <img src="{{ Thumbnail::set('slider')->src($slide->image, 's3')->urlSafe('desktop') }}"
                 alt="Hero Slide"
                 loading="lazy">
        </div>
    @endforeach
</div>

βš™οΈ Advanced Configuration

Multi-Disk Setup

// config/filesystems.php
'disks' => [
    's3_products' => [
        'driver' => 'scoped',
        'disk' => 's3',
        'prefix' => 'products',
    ],
    's3_gallery' => [
        'driver' => 'scoped',
        'disk' => 's3',
        'prefix' => 'gallery',
    ],
],

Preset Configuration

// config/thumbnails.php
'presets' => [
    'products' => [
        'format' => 'webp',
        'smartcrop' => '400x400',
        'destination' => ['disk' => 's3_products', 'path' => 'thumbnails/'],
        'quality' => 90,
        'smart_crop_enabled' => true,
        'silent_mode' => false, // Strict for admin
        'subdirectory_strategy' => 'hash_prefix', // Optimal for high volume
        'variants' => [
            'thumb' => ['smartcrop' => '120x120', 'quality' => 75],
            'card' => ['smartcrop' => '250x250', 'quality' => 85],
            'detail' => ['smartcrop' => '600x600', 'quality' => 95],
            'zoom' => ['smartcrop' => '1200x1200', 'quality' => 95],
        ]
    ],
],

AVIF Format Support

The package now supports AVIF format for next-generation image compression with superior quality-to-size ratio.

// config/thumbnails.php
'presets' => [
    'gallery' => [
        'format' => 'avif', // Use AVIF for maximum compression
        'smartcrop' => '800x600',
        'destination' => ['disk' => 'public', 'path' => 'thumbnails/gallery/'],
        'quality' => 85, // AVIF quality (0-100, 85 recommended)
        'smart_crop_enabled' => true,
    ],
],

Requirements for AVIF:

  • ImageMagick driver required (GD does not support AVIF)
  • ImageMagick library compiled with AVIF support
  • Install: pecl install imagick

Enable ImageMagick driver:

// config/thumbnails.php
'intervention_driver' => 'imagick', // Changed from 'gd'

AVIF Benefits:

  • πŸ“‰ 50% smaller file sizes vs JPEG at same quality
  • πŸ“‰ 30% smaller than WebP in most cases
  • 🎨 Better quality at lower file sizes
  • 🌐 Growing browser support (90%+ as of 2025)

Format Comparison:

Format File Size Quality Browser Support Best For
AVIF Smallest Excellent 90%+ Modern web, performance-critical
WebP Small Very Good 95%+ General purpose, wide support
JPEG Medium Good 100% Legacy compatibility
PNG Large Perfect 100% Transparency, lossless

πŸ“ Subdirectory Organization

Handle millions of thumbnails efficiently with automatic subdirectory organization:

Hash Prefix Strategy (Recommended)

thumbnails/products/
β”œβ”€β”€ a/b/ (47 files)
β”œβ”€β”€ c/d/ (52 files)
β”œβ”€β”€ e/f/ (48 files)
└── ... (256 total directories)

Date-Based Strategy

thumbnails/blog/
β”œβ”€β”€ 2025/01/28/ (today's posts)
β”œβ”€β”€ 2025/01/27/ (yesterday's posts)
└── 2025/01/26/ (older posts)

Configuration

'subdirectory_strategy' => 'hash_prefix',    // Uniform distribution (recommended)
'subdirectory_strategy' => 'date_based',     // Organized by date
'subdirectory_strategy' => 'filename_prefix', // By filename initials
'subdirectory_strategy' => 'hash_levels',    // Multi-level (a/b/c/)
'subdirectory_strategy' => 'none',           // No subdirectories

🧠 Smart Crop Algorithm

Advanced intelligent cropping based on image energy analysis:

// Enable smart crop for better results
'smart_crop_enabled' => true,  // Uses energy detection algorithm
'smart_crop_enabled' => false, // Uses simple center crop

How it works:

  • Analyzes image energy using gradient magnitude
  • Finds areas of interest based on contrast and details
  • Avoids aggressive cropping that removes important subjects
  • Uses rule of thirds for optimal positioning

πŸ› οΈ Artisan Commands

Purge Thumbnails

# Purge all thumbnails
php artisan thumbnail:purge

# Purge specific preset
php artisan thumbnail:purge products

# Silent purge (no confirmation)
php artisan thumbnail:purge products --confirm

Statistics & Analysis

php artisan tinker
>>> Thumbnail::analyzeDistribution('products')
>>> Thumbnail::getSystemStats()
>>> Thumbnail::optimize() // Remove duplicates and empty directories

πŸŽ›οΈ Advanced Features

Conditional Error Handling

{{-- Admin sees errors, users get safe fallbacks --}}
@admin
    <img src="{{ Thumbnail::strict()->set('gallery')->src($image, 's3')->url() }}" alt="Gallery">
@else
    <img src="{{ Thumbnail::silent()->set('gallery')->src($image, 's3')->url() }}" alt="Gallery">
@endadmin

Performance Optimization

// config/thumbnails.php
'optimization_profiles' => [
    'high_volume' => [
        'subdirectory_strategy' => 'hash_prefix',
        'quality' => 75,
        'silent_mode' => true,
    ],
    'high_quality' => [
        'quality' => 95,
        'webp_lossless' => true,
        'silent_mode' => false,
    ],
],

Batch Processing

// Process multiple thumbnails efficiently
'batch_size' => 50,
'batch_timeout' => 300,
'queue_enabled' => true, // Use Laravel queues

Security Features

'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif'],
'max_file_size' => 10 * 1024 * 1024, // 10MB
'validate_image_content' => true,
'sanitize_filenames' => true,

πŸ“Š Monitoring & Statistics

System Analysis

// Get complete system statistics
$stats = Thumbnail::getSystemStats();
// Returns: total files, size, distribution by disk, preset analysis

// Analyze specific preset
$analysis = Thumbnail::analyzeDistribution('products');
// Returns: file count, size, directory distribution, format breakdown

Performance Monitoring

'enable_stats' => true,
'log_generation_time' => true,
'monitor_disk_usage' => true,

πŸ”§ Troubleshooting

Common Issues

# Test disk connectivity
php artisan tinker
>>> Thumbnail::testDisk('s3_products')

# Validate configuration
>>> Thumbnail::validateConfiguration()

# Clear Laravel caches
php artisan config:clear
php artisan cache:clear

Debug Mode

{{-- Debug information in development --}}
@if(app()->environment('local'))
    @foreach(Thumbnail::getAvailableDisks() as $disk)
        @php $status = Thumbnail::testDisk($disk) @endphp
        <p>{{ $disk }}: {{ $status['accessible'] ? 'βœ…' : '❌' }}</p>
    @endforeach
@endif

πŸ“ˆ Performance Benefits

Files Without Subdirectories With Hash Prefix
1,000 ⚠️ Slow βœ… Fast
10,000 ❌ Very Slow βœ… Fast
100,000 ❌ Unusable βœ… Fast
1,000,000 ❌ Impossible βœ… Fast

With subdirectories:

  • πŸ“ˆ 200x faster filesystem operations
  • πŸš€ Instant directory listings
  • ⚑ Efficient backup and sync
  • 🎯 Optimal for CDN delivery

πŸ”„ Upgrade Guide

Upgrading to Latest Version (Intervention Image 3.x)

The latest version includes major improvements while maintaining 100% backward compatibility. No code changes are required!

What Changed

βœ… Automatic Improvements (No action required)

  • Intervention Image upgraded from 2.x to 3.x
  • Cache system now uses tags for targeted invalidation
  • Memory management improved
  • Smart crop algorithm enhanced

Recommended Actions

1. Update Dependencies

composer update askancy/laravel-smart-thumbnails

2. Configure Cache Driver (For optimal cache tagging)

If using file or database cache drivers, consider upgrading to Redis or Memcached for cache tagging support:

// config/cache.php
'default' => env('CACHE_DRIVER', 'redis'), // or 'memcached'

Cache drivers that support tagging:

  • βœ… Redis (recommended)
  • βœ… Memcached
  • βœ… Array (testing only)
  • ❌ File (falls back to non-tagged cache)
  • ❌ Database (falls back to non-tagged cache)

3. Optional: Enable ImageMagick (Better quality + AVIF support)

# Install ImageMagick extension
pecl install imagick

# Then update config
// config/thumbnails.php
'intervention_driver' => 'imagick', // Changed from 'gd'

Note: ImageMagick is required if you want to use the new AVIF format, which offers superior compression and quality. See the AVIF Format Support section for details.

4. Verify Configuration

php artisan tinker
>>> Thumbnail::validateConfiguration()

New Configuration Options

Add these to your config/thumbnails.php (optional, defaults shown):

/*
|--------------------------------------------------------------------------
| Cache Settings
|--------------------------------------------------------------------------
*/
'cache_urls' => true,        // Enable URL caching
'cache_ttl' => 3600,         // Cache TTL in seconds (1 hour)

Breaking Changes

None! This is a fully backward-compatible update.

Troubleshooting

Issue: Cache not working after upgrade

# Clear Laravel cache
php artisan cache:clear
php artisan config:clear

Issue: "Driver not found" error

# Install Intervention Image GD driver
composer require intervention/image-gd

# Or for ImageMagick
composer require intervention/image-imagick

Issue: Thumbnails not generating

# Test your configuration
php artisan tinker
>>> Thumbnail::set('gallery')->debugInfo()

Performance Optimization Tips

1. Warm up cache for existing thumbnails:

// In a command or controller
$images = ['image1.jpg', 'image2.jpg', ...];
$results = Thumbnail::warmUpCache($images, 'gallery', ['thumb', 'medium']);
// Returns: ['warmed' => 50, 'already_cached' => 25, 'errors' => 0]

2. Use preset-specific cache clearing:

// Clear only thumbnails cache (not entire app cache)
Cache::tags(['thumbnails'])->flush();

// Clear specific preset cache
Cache::tags(['thumbnails', 'gallery'])->flush();

3. Monitor cache performance:

$metrics = Thumbnail::set('gallery')->src('photo.jpg')->getPerformanceMetrics();
// Returns execution time, memory usage, cache hit/miss info

πŸš€ Roadmap & Development Status

Smart Crop Enhancements

We have exciting enhancements planned for the smart crop algorithm! See SMART_CROP_ROADMAP.md for:

  • 🎯 Edge Detection - Sobel filter for identifying image edges
  • 🧠 Entropy Analysis - Texture and detail detection
  • πŸ‘€ Face Detection - Automatic face preservation
  • πŸ—ΊοΈ Saliency Maps - Visual attention modeling
  • πŸ€– Machine Learning - AI-powered object detection

Current Development Tasks

See TODO.md for the complete development roadmap including:

  • βœ… Core improvements (Intervention Image 3.x, cache tagging) - COMPLETED
  • πŸ”΄ High priority tasks (tests, CI/CD, documentation)
  • 🟑 Medium priority (code quality, examples)
  • 🟒 Future features (CDN integration, admin panel)

Contributions welcome! Check the roadmap for implementation details and priorities.

🀝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for details.

For implementing smart crop enhancements, refer to SMART_CROP_ROADMAP.md.

πŸ“„ License

MIT License. See LICENSE.md for details.

πŸ™ Credits

πŸ’‘ Pro Tip: Always use urlSafe() or silent() for public-facing content and reserve strict() mode for admin interfaces and development!