Intervention Image has optional support for Laravel and comes with a Service Provider and Facades for easy integration. The vendor/autoload.php
is included by Laravel, so you don’t have to require or autoload manually. intervention/image package is used to upload and resize the images. Very usefull and powerfull package in laravel.
Install Intervention Image Package
composer require intervention/image
Find the providers in config >> app.php file and register the ImageServiceProvider.
'providers' => [
// ...
'Intervention\Image\ImageServiceProvider',
]
Locate the aliases in config >> app.php file and register the aliases.
'aliases' => [
// ...
'Image' => 'Intervention\Image\Facades\Image',
]
Controller ==> Save Data into Database
use Image;
public function store(Request $request)
{
$originalImage= $request->file('filename');
$thumbnailImage = Image::make($originalImage);
$thumbnailPath = public_path().'/thumbnail/';
$originalPath = public_path().'/images/';
$thumbnailImage->save($originalPath.time().$originalImage->getClientOriginalName());
$thumbnailImage->resize(150,150);
$thumbnailImage->save($thumbnailPath.time().$originalImage->getClientOriginalName());
$imagemodel= new ImageModel();
$imagemodel->filename=time().$originalImage->getClientOriginalName();
$imagemodel->save();
return back()->with('success', 'Your images has been successfully Upload');
}
Validation in Controller
public function store(Request $request)
{
$this->validate($request, [
'filename' => 'image|required|mimes:jpeg,png,jpg,gif,svg'
]);
}
My Custom Traits – Resize and Random File Name
use Image;
trait LaraResize {
public function laraResize($file,$width,$height,$destination)
{
$extension = $file->getClientOriginalExtension();
$rnd_file_name_with_ext_and_location = $this->getLaraRandomFileName($destination,$extension);
$img = Image::make($file);
$img->resize($width,$height);
$img->save($rnd_file_name_with_ext_and_location);
return $rnd_file_name_with_ext_and_location;
}
public function getLaraRandomFileName($destination,$ext)
{
$random_file_name = strtolower(str_random(25));
$file_name = $destination .'/'.$random_file_name.'.'.$ext;
if(app('files')->exists($file_name)){
return $this->getLaraRandomFileName($destination,$ext);
}
return $file_name .'.'.$ext;
}
}
My Custom Controller – To Call above Traits To Upload The File
$data['image'] = $this->laraResize($request->file('image'),640,460,'img/project');