I have working code for saving image until I decided to add a resize function. I have already done the following:
composer require intervention/image
added this on $providers
Intervention\Image\ImageServiceProvider::class
and this on $aliases
'Image' => Intervention\Image\Facades\Image::class
on my controller I add this
use Intervention\Image\ImageManagerStatic as Image;
but actually I don't know where to put the resize ( "resize(900, 900);" ) so I have this,
public function update_avatar(Request $request){
$request->validate([
'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2012',
]);
$user = Auth::User();
if($user->avatar !== 'user.jpg'){
$folder = 'avatars';
Storage::delete($folder.'/'.$user->avatar);
}
$avatarName = $user->id.'_avatar'.'.'.request()->avatar->getClientOriginalExtension();
$request->avatar->resize(900, 900);
$request->avatar->storeAs('avatars',$avatarName);
$user->avatar = $avatarName;
$user->save();
return back()
->with('success','You have successfully upload image.');
}
and here's the error
can anyone help me to figure this out? Thank you so much in advance.
SOLUTION base from @Snapey
$canvas = Image::canvas(900, 900);
$image = Image::make($request->avatar);
$image->resize(900,900,
function($constraint)
{
$constraint->aspectRatio();
});
$canvas->insert($image, 'center');
$path = Storage::path('avatars');
$canvas->save($path . '/' . $avatarName);
I added a canvas so that the photo will remain proportional instead of look stretched image.
CodePudding user response:
You need to create an Intervention Image object from the uploaded file, then resize and save it
$avatarName = $user->id.'_avatar'.'.'.request()->avatar->getClientOriginalExtension();
$image = Image::make($request->avatar);
$image->resize(900, 900);
$path = Storage::disk('avatars')->path();
$image->save($path . '/' . $avatarName);