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
Requires
- php: ^8.1
- ext-gd: *
- intervention/image: ^3.9
- intervention/image-gd: ^1.0
- laravel/framework: ^10.0|^11.0|^12.0
Requires (Dev)
- mockery/mockery: ^1.6
- orchestra/testbench: ^8.0|^9.0
- phpunit/phpunit: ^10.0|^11.0
Suggests
- ext-imagick: For advanced image processing capabilities and AVIF format support
- ext-memcached: For cache tagging support with Memcached driver
- ext-redis: For cache tagging support with Redis driver
- intervention/image-imagick: For better image quality, AVIF format support, and more features (requires ext-imagick)
README
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.
β¨ 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
ThumbnailGeneratorutility 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()orsilent()for public-facing content and reservestrict()mode for admin interfaces and development!