Home  >  Q&A  >  body text

Resize image before upload in Laravel 5.8

<p>I have this function to upload images via api in Laravel: </p> <pre class="brush:php;toolbar:false;">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; }</pre> <p>How do I resize an image to a maximum side length of 500 pixels before uploading? </p>
P粉608647033P粉608647033434 days ago550

reply all(1)I'll reply

  • P粉153503989

    P粉1535039892023-09-05 11:18:07

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

    1. Install software package:

      Composer Needs Intervention/Image

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

      Use Intervention\Image\ImageManagerStatic as image;

      Use Illuminate\Support\Str;

    3. Modify the handleImage method as follows:

      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 helps you

    reply
    0
  • Cancelreply