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

Laravel Thumbnail Laravel Package

shishima/laravel-thumbnail

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require shishima/laravel-thumbnail
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Shishima\Thumbnail\ThumbnailServiceProvider"
    
  2. System Requirements

    • Ensure your Linux environment has:
      • 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)
      • PHP imagick extension (sudo apt install php-imagick + restart server)
    • Copy policy.xml to /etc/ImageMagick-6/ and Module1.xba to /usr/lib/libreoffice/presets/basic/Standard/.
  3. 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');
    

Implementation Patterns

Core Workflows

  1. 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');
    
  2. 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!');
    }
    
  3. 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));
    }
    
  4. 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());
    
  5. 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');
    

Integration Tips

  • 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">
    

Gotchas and Tips

Pitfalls

  1. Linux-Only Dependency

    • The package will not work on Windows/macOS without a Linux environment (e.g., Docker, VPS, or WSL with shared folders).
    • Workaround: Use a microservice or serverless function (e.g., AWS Lambda with Docker) for thumbnail generation.
  2. Missing Dependencies

    • Forgetting to install libreoffice, unoconv, or ghostscript will cause failures for DOCX/XLSX files.
    • Debug Tip: Check logs for unoconv or libreoffice errors (e.g., Failed to convert file).
  3. Imagick Permissions

    • If PDF thumbnails fail, ensure policy.xml is correctly placed in /etc/ImageMagick-6/ and grants PDF read/write permissions:
      <policy domain="coder" rights="read|write" pattern="PDF" />
      
    • Restart the web server after changes:
      sudo service apache2 restart  # or nginx/php-fpm
      
  4. Memory Limits

    • Large files (e.g., multi-page PDFs) may hit PHP’s memory_limit. Increase it in php.ini:
      memory_limit = 512M
      
  5. File Path Issues

    • Thumbnail generation fails silently if the input file path is invalid or inaccessible.
    • Debug Tip: Log the full path and verify file permissions:
      if (!file_exists($path)) {
          Log::error("File not found: {$path}");
      }
      
  6. Excel Line Break Bug

    • Without Module1.xba, Excel thumbnails may have misaligned text.
    • Fix: Copy the file to /usr/lib/libreoffice/presets/basic/Standard/ and restart LibreOffice:
      sudo systemctl restart libreoffice
      

Debugging

  1. Enable Imagick Debugging Add to config/thumbnail.php:

    'debug' => true,
    

    Check Laravel logs for Imagick commands and errors.

  2. 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'));
    
  3. Check unoconv Output Run unoconv manually to test conversion:

    unoconv -f pdf test.docx
    

    If this fails, the issue is with LibreOffice/unoconv setup.


Extension Points

  1. 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();
        }
    }
    
  2. 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.

  3. Override Storage Bind a custom storage disk in AppServiceProvider:

    Thumbnail::extend('s3', function () {
        return new S3ThumbnailService();
    });
    
  4. 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");
    }
    

Performance Tips

  1. Optimize Image Quality Reduce JPEG quality to save space:

    Thumbnail::make('file.jpg')->quality(80)->thumbnail()->save('thumb.jpg');
    
  2. Lazy Loading Generate thumbnails on-demand (e.g., via a route) instead of pre-generating for all files.

  3. Parallel Processing Use Laravel’s `parallel

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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium