Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Resize image before uploading in Laravel 5.8

I have this function for upload image via api in Laravel:

private function handleImage($image)
    {
        $exploded = explode(',', $image);

        $decoded = base64_decode($exploded[1]);

        if (Str::contains($exploded[0], 'jpeg')) {
            $extension = 'jpg';
        } else {
            $extension = 'png';
        }
        $fileName = Str::random() . '.' . $extension;

        $path = public_path() . '/images/products/' . $fileName;

        $file = file_put_contents($path, $decoded);

        $image = '/images/products/' . $fileName;

        return $image;
    }

How can I resize image to size with max side 500px before uploading?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try the Intervention Image package in Laravel to resize before uploading.

  1. Install the package:

    composer require intervention/image

  2. Add the below code at the beginning of your file to import the required classes:

    use Intervention\Image\ImageManagerStatic as Image;

    use Illuminate\Support\Str;

  3. Modify the handleImage method like below:

    private function handleImage($image)
     {
     $exploded = explode(',', $image);
     $decoded = base64_decode($exploded[1]);
     $image = Image::make($decoded);
    
     // Resize the image to a maximum size of 500px on the longest side
     $image->resize(500, null, function ($constraint) {
         $constraint->aspectRatio();
         $constraint->upsize();
     });
    
     // Set the file extension based on the original image format
     if (Str::contains($exploded[0], 'jpeg')) {
         $extension = 'jpg';
     } else {
         $extension = 'png';
     }
    
     $fileName = Str::random() . '.' . $extension;
     $path = public_path() . '/images/products/' . $fileName;
     $image->save($path);
    
     return '/images/products/' . $fileName;
    }
    

https://github.com/Intervention/image

Hope it may help

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading