How to reduce size of image in laravel when upload?

by wilmer.lemke , in category: PHP Frameworks , a month ago

How to reduce size of image in laravel when upload?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , a month ago

@wilmer.lemke 

You can reduce the size of an image in Laravel when uploading by using the Intervention Image library. Here's a step-by-step guide on how to do it:

  1. Install the Intervention Image library by running the following composer command in your Laravel project:
1
composer require intervention/image


  1. Once the library is installed, you can use it in your controller when uploading an image. Here's an example code snippet that shows how to reduce the size of an image before uploading it:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use InterventionImageImageManagerStatic as Image;

public function uploadImage(Request $request)
{
    // Get the uploaded file
    $image = $request->file('image');

    // Resize the image
    $img = Image::make($image->getRealPath());
    $img->resize(300, 200)->save();

    // Move the image to the desired location
    $imageName = time() . '.' . $image->getClientOriginalExtension();
    $image->move(public_path('images'), $imageName);

    // Save the image path in the database
    $imagePath = 'images/' . $imageName;

    // Save the image path in the database
    Image::create([
        'path' => $imagePath
    ]);

    return response()->json(['message' => 'Image uploaded successfully']);
}


In the above code snippet, we resize the image to a width of 300 pixels and height of 200 pixels before saving it. You can adjust the resize dimensions according to your requirements.

  1. Make sure to include the necessary use statement for the Intervention Image library at the top of your controller file.


By following these steps, you can reduce the size of an image when uploading it in Laravel using the Intervention Image library.