
Инсталиране на Intervention\Image
:
composer require intervention/image
В Laravel > 5.4 автоматично се регистрират пакетите.
Функция за ъплоуд на изображения - с проверка и преоразмеряване ако снимката е над 1200 пиксела по ширина или височина със запазване на съотношението на изображението:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Image;
class ImageUploadController extends Controller
{
protected $file;
protected $filename_to_store;
protected $dir_to_store;
protected $image_path;
protected $image_width = 1200;
protected $image_height = 1200;
public function storeImage(Request $request)
{
request()->validate(['image' => ['required', 'image', 'mimes:jpeg,png,jpg,gif,svg']]);
$this->getPaths($request->file('image'));
$this->uploadImage();
return response(asset('storage/'.$this->image_path), 200);
}
public function storeIcon(Request $request)
{
request()->validate(['icon' => ['required', 'image', 'mimes:jpeg,png,jpg,gif,svg']]);
$this->getPaths($request->file('icon'), 'icons');
$this->image_width = 120;
$this->image_height = 120;
$this->uploadImage();
return response(asset('storage/'.$this->image_path), 200);
}
private function getPaths($file, $type = 'images')
{
$this->file = $file;
$this->dir_to_store = $type . '/' . date('Y/m/d/');
Storage::makeDirectory('public/' . $this->dir_to_store);
$filename = pathinfo($this->file->getClientOriginalName(), PATHINFO_FILENAME);
$this->filename_to_store = $filename . '_' . time() . '.' . $this->file->getClientOriginalExtension();
$this->image_path = $this->dir_to_store . $this->filename_to_store;
}
private function uploadImage()
{
$img = Image::make($this->file);
$img->height() > $img->width() ? $this->image_width=null : $this->image_height=null;
$img->resize($this->image_width, $this->image_height, function ($constraint) {
$constraint->aspectRatio();
})
->save('storage/'. $this->image_path);
}
}