How to resize image before upload in Laravel?

Member

by addison , in category: PHP Frameworks , 9 months ago

How to resize image before upload in Laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 3 months ago

@addison 

To resize an image before uploading it in Laravel, you can use the intervention/image package. This package provides a simple interface for resizing and manipulating images.


Here's an example of how you can use the intervention/image package to resize an image before uploading it in Laravel:

  1. First, install the intervention/image package by running the following command in your terminal:
1
composer require intervention/image


  1. Next, add the following line to the providers array in your config/app.php file:
1
InterventionImageImageServiceProvider::class


  1. In the same config/app.php file, add the following line to the aliases array:
1
'Image' => InterventionImageFacadesImage::class


  1. In your Laravel controller, you can now use the Image facade to open and resize the image:
1
2
3
4
5
6
7
use Image;

// Open and resize the image
$image = Image::make($request->file('image'))->resize(300, 300);

// Save the resized image
$image->save(public_path('uploads/' . $image->filename));


This code will open the image file specified in the request, resize it to 300x300 pixels, and save it to the uploads folder in the public directory.


You can also customize the resizing process by using the various methods available in the Image class. For example, you can use the fit() method to resize the image while preserving the aspect ratio, or the crop() method to crop the image to a specific size.


For more information on using the intervention/image package to manipulate images in Laravel, you can refer to the documentation at https://image.intervention.io/.