I'm trying to reduce the size of the images uploaded by users on a project I'm working on. The main idea is to resize the image down by 10%, and checking if its size is under a set requirement.
Here is my code: ($optimisedImage is the original image uploaded by the user and recieved from the request)
$optimisedImage->save("user_uploads/" . $scrollFeedName);
$scrollFeedImg = Image::make("user_uploads/" . $scrollFeedName);
while(filesize("user_uploads/" . $scrollFeedName) > 1000000) {
$scrollFeedImg->resize(floor($scrollFeedImg->width() * 0.9), floor($scrollFeedImg->height() * 0.9));
$scrollFeedImg->save();
}
Currently there seems to be an issue with the loop, getting stuck. I also tried the Intervention Image filesize(), but was getting an error stating that the width or heigth need to be higher than 0.
Is there any way to achieve my goal, or are there better solutions to that problem?
Stack:
PHP: 8.1.10
Laravel: 9.19
Step 1: Install intervention for resize image
composer require intervention/image
Step 2: Add provider path and alias path in config/app.php
return [
$provides => [
'Intervention\Image\ImageServiceProvider'
],
$aliases => [
'Image' => 'Intervention\Image\Facades\Image'
]
];
Step 3: Resize Image code for controller
public function resizeImagePost(Request $request) {
$this->validate($request, [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$input['imagename'] = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/thumbnail');
$img = Image::make($image->getRealPath());
$img->resize(100, 100, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input['imagename']);
$destinationPath = public_path('/images');
$image->move($destinationPath, $input['imagename']);
$this->postImage->add($input);
return back()
->with('success','Image Upload successful')
->with('imageName',$input['imagename']);
}
Related
I realize this question has been asked several times on this forum, but none of the solutions given has resolved my particular issue.
I get the above error when trying to update my DB.
Here is a snippet of my code
I have tried adding findorfail on my request by id
$service=Service::findorfail($request->input('id'));
This returns a 404 page.
ServiceController.php
public function updateService(Request $request){
// return $request->all();
$this->validate($request, ['serviceTitle'=> 'required',
'serviceSubTitle'=> 'required',
'description'=> 'required',
'slug' => 'required|min:3|max:255|unique:services',
'serviceImage'=>'image|nullable|max:1999']);
$service=Service::find($request->input('id'));
$service->title =$request->input('serviceTitle');
$service->sub_title =$request->input('serviceSubTitle');
$service->slug =$request->input('slug');
$service->description =$request->input('description');
if($request->hasFile('serviceImage')) {
//1 : get filename with ext
$fileNameWithExt = $request->file('serviceImage')->getClientOriginalName();
//2 : get just file name
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//3 : get just extension
$extension = $request->file('serviceImage')->getClientOriginalExtension();
//4: filename to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload image
$path =$request->file('serviceImage')->storeAs('public/serviceImage', $fileNameToStore);
$old_image =Service::find($request->input('id'));
if($old_image!='noimage.jpg') {
Storage::delete('public/serviceImage/'.$old_image->image);
}
$service->image =$fileNameToStore;
}
$service->update();
return redirect('/services')->with('status', 'The '.$service->title.' Service has been updated successfully');
}
The error log tells me the error is on this specific line:
$service->title =$request->input('serviceTitle');
Thank you for time and assistance.
I am creating a controller that saves photos to the /storage/ folder. To protect myself from submitting a bunch of large photos and not to style their CSS, I wanted to resize them using the Intervention / image library. Unfortunately, despite following the installation instructions directly from the documentation, several uninstallations and reinstallations of the library do not work. When I use this code snippet:
Use Image;
I get an error saying:
Undefined type 'Image'
Following the instructions, I added the following to /config/app.php:
'providers' => [
...
Intervention\Image\ImageServiceProvider::class,
],
'aliases' => [
...
'Image' => Intervention\Image\Facades\Image::class,
...
],
Besides, I cleaned and reconfigured the cache and config, restarted the server, tried to use:
use Intervention\Image\ImageManagerStatic as Image;
But unfortunately that didn't help either.
What am I doing wrong?
You have to use the namespace below
use Intervention\Image\Facades\Image;
Then you can use like-
$image = $request->file('image');
$ext = $image->getClientOriginalExtension();
$img = Image::make($image)->resize(300, 200)->save('storage/folder/filename'.'.'.$ext);
Use Image facade directly
\Intervention\Image\Facades\Image::make(\File::get($file_address))
->fit($width, $height)
->save($path_for_saving);
You can fit or crop the image based on your needs.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
public function imageUploadPost(Request $request)
{
$photo = $request->file('image');
$imagename = time() . '.' . $photo->getClientOriginalExtension();
// Upload Crop Image...
$destinationPath = public_path('uploads/thumbnail_images');
if (!File::isDirectory($destinationPath)) {
File::makeDirectory($destinationPath, 0777, true, true);
}
$thumb_img = \Intervention\Image\Facades\Image::make($photo->getRealPath())->resize(100, 100);
$thumb_img->save($destinationPath . '/' . $imagename, 100); // Define Quality 100 (Optional)
echo '<pre>';
print_r("Upload Successfully. Store File : laravel_project/public/uploads & laravel_project/public/uploads/thumbnail_images");
}
I am Try to Upload User Avatar with Intervention Image as below private function
Everything working fine but image name save to database with my specific folder name
eg : user_avatar/image.jpg
Here is My Code Thanks everyone
private function storeAvatar($user)
{
if (request()->hasFile('avatar')) {
$user->update([
'avatar' => request()->avatar->store('user_avatar', 'public'),
]);
$avatar = Image::make(public_path('storage/' .$user->avatar))->fit(300, 300);
$avatar->save();
}
}
enter image description here
You're not setting a file name.
$path = $request->file('avatar')->storeAs(
'avatars', $request->user()->id
);
As indicated here: https://laravel.com/docs/7.x/filesystem#file-uploads
So your line should be:
$user->update([
'avatar' => request()->avatar->storeAs('user_avatar', 'filename', 'public'),
]);
Or something along those lines. You can also use the file name as uploaded by making the filename the same as the original.
$filename = $request->file('avatar')->getClientOriginalName();
I'm working on a Laravel project, and I make a feature that the user can upload image for its profile, and I use the public path to save the avatars cause 000webhost doesn't support (storage:link) and every thing works better in local
but when I upload the project on 000webhost, it refuses to upload the image and returns error (The image failed to upload.)
How can i solve it
config/filesystem.php
'public' => [
'driver' => 'local',
'root' => public_path('storage2'),
'url' => env('APP_URL').'/storage2',
'visibility' => 'public',
],
controller
public function Change(Request $request)
{
$Validate = $this->Validation($request);
if (!$Validate->fails()) {
$User = $this->getUser();
$OldImage = $User->image;
$Extension = $request->file("image")->getClientOriginalExtension();
$NewImage = str_random(30) . "." . $Extension;
Storage::putFileAs($this->privatePath, $request->file("image"), $NewImage);
$User->update(["image" => $NewImage]);
Storage::delete($this->privatePath ."/". $OldImage);
session()->flash("message", "You have changed your image");
return back();
} else {
session()->flash("error", $Validate->errors()->first());
return back();
}
}
But the problem is not in the code, cause it works in local
I think the problem with some permissions or in file .htaccess or anything like that
I want to add a watermark to my uploaded image using intervention image library in laravel.I have installed it through command composer require intervention/image
, added Intervention\Image\ImageServiceProvider::class in providers array and 'Image' => Intervention\Image\Facades\Image::class in aliases array.
This is my code sample:
if($request->file1)
{
$this->validate($request, [
'file1' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
]);
$imageName = time().'-'.rand(11111, 99999).'.'.$request->file1->getClientOriginalExtension();
$imageName = $imageName->insert('https://www.exabytes.my/wp-content/uploads/400x150-exabytes-logo.png','center');
$request->file1->move('theme/img/properties', $imageName);
}
You have to actually use the Image class/facade:
$imageName = time().'-'.rand(11111, 99999).'.'.$request->file1->getClientOriginalExtension();
$file = $request->file1->move('theme/img/properties', $imageName);
$source = 'https://www.exabytes.my/wp-content/uploads/400x150-exabytes-logo.png';
Image::make($file->getPath())->insert($source, 'center');