Installation
composer require shishima/laravel-thumbnail
Publish the config file (if needed):
php artisan vendor:publish --provider="Shishima\Thumbnail\ThumbnailServiceProvider"
System Requirements
libmagickwand-dev (sudo apt-get install libmagickwand-dev)ghostscript (sudo apt-get install ghostscript)libreoffice (sudo apt-get install libreoffice)unoconv (sudo apt-get install unoconv)imagick extension (sudo apt install php-imagick + restart server)policy.xml to /etc/ImageMagick-6/ and Module1.xba to /usr/lib/libreoffice/presets/basic/Standard/.First Use Case Generate a thumbnail from a file (e.g., PDF, DOCX, or image):
use Shishima\Thumbnail\Facades\Thumbnail;
$path = 'path/to/your/file.pdf';
$thumbnail = Thumbnail::make($path)->thumbnail();
$thumbnail->save('path/to/output.jpg');
Generating Thumbnails
// Basic usage
$thumbnail = Thumbnail::make('file.pdf')->thumbnail();
$thumbnail->save('thumbnail.jpg');
// Custom dimensions (width/height in pixels)
Thumbnail::make('file.xlsx')->resize(200, 200)->thumbnail()->save('custom.jpg');
// Force square thumbnails (maintain aspect ratio)
Thumbnail::make('file.docx')->fit(200, 200)->thumbnail()->save('square.jpg');
Handling File Uploads
// In a controller (e.g., for user-uploaded files)
public function upload(Request $request) {
$file = $request->file('document');
$path = $file->store('uploads');
$thumbnail = Thumbnail::make(storage_path("app/{$path}"))
->thumbnail()
->save(storage_path("app/public/thumbs/{$file->hashName()}.jpg"));
return redirect()->back()->with('success', 'Thumbnail generated!');
}
Batch Processing
// Process multiple files (e.g., from a directory)
$files = Storage::disk('local')->files('documents/');
foreach ($files as $file) {
$thumbnail = Thumbnail::make(storage_path("app/{$file}"))
->resize(300, 300)
->thumbnail()
->save(str_replace('documents', 'thumbs', $file));
}
Integration with Storage
// Save directly to cloud storage (e.g., S3)
use Illuminate\Support\Facades\Storage;
$thumbnail = Thumbnail::make('file.pdf')->thumbnail();
Storage::disk('s3')->put('thumbs/file.jpg', $thumbnail->stream());
Dynamic Thumbnail URLs
// Generate URLs for dynamically generated thumbnails
$url = route('thumbnails.generate', ['file' => 'document.pdf']);
// In routes/web.php:
Route::get('/thumbnails/{file}', [ThumbnailController::class, 'generate'])->name('thumbnails.generate');
Queue Jobs for Large Files Offload thumbnail generation to a queue (e.g., Laravel Queues) to avoid timeouts:
ThumbnailJob::dispatch($filePath, $outputPath)->onQueue('thumbnails');
Cache Thumbnails Use Laravel’s cache to avoid regenerating thumbnails for the same file:
$cacheKey = 'thumbnail_' . md5($filePath);
if (!Cache::has($cacheKey)) {
$thumbnail = Thumbnail::make($filePath)->thumbnail();
Cache::put($cacheKey, $thumbnail->stream(), now()->addHours(1));
}
Laravel Nova/Eloquent Integration Attach thumbnails to Eloquent models:
// In a model observer or accessor
public function getThumbnailAttribute() {
$path = storage_path("app/{$this->file_path}");
$thumbnail = Thumbnail::make($path)->resize(150, 150)->thumbnail();
return $thumbnail->stream();
}
Frontend Display Use Blade directives to embed thumbnails:
<img src="{{ Thumbnail::make('file.pdf')->thumbnail()->toBase64() }}" alt="Thumbnail">
Linux-Only Dependency
Missing Dependencies
libreoffice, unoconv, or ghostscript will cause failures for DOCX/XLSX files.unoconv or libreoffice errors (e.g., Failed to convert file).Imagick Permissions
policy.xml is correctly placed in /etc/ImageMagick-6/ and grants PDF read/write permissions:
<policy domain="coder" rights="read|write" pattern="PDF" />
sudo service apache2 restart # or nginx/php-fpm
Memory Limits
memory_limit. Increase it in php.ini:
memory_limit = 512M
File Path Issues
if (!file_exists($path)) {
Log::error("File not found: {$path}");
}
Excel Line Break Bug
Module1.xba, Excel thumbnails may have misaligned text./usr/lib/libreoffice/presets/basic/Standard/ and restart LibreOffice:
sudo systemctl restart libreoffice
Enable Imagick Debugging
Add to config/thumbnail.php:
'debug' => true,
Check Laravel logs for Imagick commands and errors.
Test with Known Files
Use a small test file (e.g., test.pdf) to isolate issues:
Thumbnail::make(public_path('test.pdf'))->thumbnail()->save(public_path('test_thumb.jpg'));
Check unoconv Output
Run unoconv manually to test conversion:
unoconv -f pdf test.docx
If this fails, the issue is with LibreOffice/unoconv setup.
Custom Thumbnail Logic
Extend the Shishima\Thumbnail\Thumbnail class to add presets:
namespace App\Services;
use Shishima\Thumbnail\Thumbnail as BaseThumbnail;
class CustomThumbnail extends BaseThumbnail {
public function socialMedia() {
return $this->resize(1200, 630)->thumbnail();
}
}
Add File Type Support
The package uses finfo to detect file types. To support additional formats (e.g., PPTX), extend the supports() method in a custom service provider.
Override Storage
Bind a custom storage disk in AppServiceProvider:
Thumbnail::extend('s3', function () {
return new S3ThumbnailService();
});
Webhook Triggers Use Laravel Events to auto-generate thumbnails on file upload:
Storage::disk('s3')->put('file.pdf', $file);
event(new FileUploaded($file));
In an event listener:
public function handle(FileUploaded $event) {
Thumbnail::make($event->file)->thumbnail()->save("thumbs/{$event->file->hashName()}.jpg");
}
Optimize Image Quality Reduce JPEG quality to save space:
Thumbnail::make('file.jpg')->quality(80)->thumbnail()->save('thumb.jpg');
Lazy Loading Generate thumbnails on-demand (e.g., via a route) instead of pre-generating for all files.
Parallel Processing Use Laravel’s `parallel
How can I help you explore Laravel packages today?