How to generate thumbnails by using Spatie Media Library

Laravel
November 28, 20202 minutesuserVishal Ribdiya
How to generate thumbnails by using Spatie Media Library

Hope you guys are familiar with Spatie Media Library. It's a very useful and time-saving package to manage file uploading.

It's also providing support to convert your images to thumbnails while storing images. you can generate a thumbnail of the image with the size (height, width) you want.

They are calling thumbnails to Conversions. You can generate multiple thumbnails with different sizes as you want.

So let's see some short examples which help us to create thumbnails of an uploaded image.

Implement the HasMediaTrait into your Model

Here we have a User model and we want to generate a thumbnail of the user uploading his profile image. you have to add HasMediaTrait to the User model and need to extend HasMedia.

use IlluminateDatabaseEloquentModel;
use SpatieMediaLibraryModelsMedia;
use SpatieMediaLibraryHasMediaHasMedia;
use SpatieMediaLibraryHasMediaHasMediaTrait;

class User extends Model implements HasMedia
{
    use HasMediaTrait;

    public function registerMediaConversions(Media $media = null)
    {
        $this->addMediaConversion('profile-thumb')
              ->width(150)
              ->height(150);
    }
}

Here we have defined a function registerMediaConversions in which we can manage the size of a thumbnail, which means how much height or width we want for the thumbnail.

So when we upload an image using the media library,

$media = User::first()->addMedia($pathToImage)->toMediaCollection();

it will auto-generate the thumbnails with the given height and width.

How to fetch the generated thumbnail?

$media->getPath();  // the path to the where the original image is stored
$media->getPath('profile-thumb') // the path to the converted image with dimensions 150*150

$media->getUrl();  // the url to the where the original image is stored
$media->getUrl('profile-thumb') // the url to the converted image with dimensions 150*150

How to generate multiple thumbnails for a single image?

..... in User Model .....
use SpatieImageManipulations;

    public function registerMediaConversions(Media $media = null)
    {
        $this->addMediaConversion('profile-thumb')
              ->width(150)
              ->height(150);
    }

        $this->addMediaConversion('old-profile-thumb')
              ->sepia()
              ->border(8, 'black', Manipulations::BORDER_OVERLAY);
    }

so, it will generate 2 thumbnails with different image properties. you can use different image properties directly while generating thumbnails.

That's it, you can read more about the spatie media library conversions (thumbnails) here.

Keep connected to us for more interesting posts about laravel.