Intervention Image - Reducing image size gradually

166 Views Asked by At

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
1

There are 1 best solutions below

1
Ankit Jindal On

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']);
    }