FEATURE: make thumbnails from uploaded image
This commit is contained in:
@@ -4,9 +4,13 @@ namespace App\Models;
|
||||
|
||||
use App\Events\UploadFile;
|
||||
use App\Http\Requests\Request;
|
||||
use Franzose\ClosureTable\Extensions\Str;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\File as FileFacade;
|
||||
use Intervention\Image\Constraint;
|
||||
use Intervention\Image\Facades\Image;
|
||||
use Symfony\Component\HttpFoundation\File\File as SymphonyFile;
|
||||
use Symfony\Component\HttpFoundation\File\UploadedFile;
|
||||
|
||||
@@ -63,6 +67,12 @@ class File extends Model
|
||||
// save file into physical location (local FS)
|
||||
$uploadedFile = $file->move($destination, $filename);
|
||||
|
||||
// is uploaded file an image?
|
||||
if (Str::startsWith($uploadedFile->getMimeType(), 'image')) {
|
||||
// yes, create thumbnail
|
||||
$this->createThumbnail($uploadedFile);
|
||||
}
|
||||
|
||||
// insert record into database
|
||||
$id = $this->saveIntoDatabase($uploadedFile, $request, $file->getClientOriginalName());
|
||||
|
||||
@@ -118,4 +128,29 @@ class File extends Model
|
||||
|
||||
return $newFile->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create thumbnail of given image
|
||||
*
|
||||
* @param SymphonyFile $file
|
||||
*/
|
||||
private function createThumbnail(SymphonyFile $file)
|
||||
{
|
||||
// does thumbnail directory exist?
|
||||
if (!is_dir(config('app.thumbnail_path'))) {
|
||||
FileFacade::makeDirectory(config('app.thumbnail_path'));
|
||||
}
|
||||
|
||||
// get image instance
|
||||
$image = Image::make(config('app.upload_path') . DIRECTORY_SEPARATOR . $file->getFilename());
|
||||
|
||||
// resize image and keep aspect ration
|
||||
$image->resize(env('THUMBNAIL_WIDTH', 300), null, function (Constraint $constraint) {
|
||||
$constraint->aspectRatio();
|
||||
$constraint->upsize();
|
||||
});
|
||||
|
||||
// save thumbnail with lower quality
|
||||
$image->save(config('app.thumbnail_path') . DIRECTORY_SEPARATOR . $file->getFilename(), 75);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user