laravellaravel-medialibrary

Prevent generating oversized media in spatie media library


I am using Spatie media library to manage media in my laravel app. The issue is it generates oversized images even if the uploaded file is small which results in pixelated images.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Spatie\Image\Manipulations;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media; 

class Post extends Model implements HasMedia
{
    use InteractsWithMedia;

    public function registerMediaConversions(Media $media = null) : void
    {
        $this->addMediaConversion('thumb')
            ->width(100);
        $this->addMediaConversion('xs')
            ->width(320);
        $this->addMediaConversion('sm')
            ->width(640);
        $this->addMediaConversion('md')
            ->width(768);
        $this->addMediaConversion('lg')
            ->width(1024);
        $this->addMediaConversion('xl')
            ->width(1280);
    }

    public function registerMediaCollections() : void
    {
        $this->addMediaCollection('images');
    }
}

Above is my model code. Suppose if I upload image of width 700 pixels, it also generates md, lg, and xl images.

How do I prevent media conversions which are greater than the uploaded image's width?


Solution

  • The following link gives the answer to this question

    Laracast forum

    if ($this->width > 768) {
        $this->addMediaConversion('md')
            ->width(768);
    }
    
    if ($this->width > 1024) {
        $this->addMediaConversion('lg')
            ->width(1024);
    }