
Resize Images using intervention-image
In this article we will learn how to install and use intervention/image in laravel.We will resize images using intervention/image package.We will upload multiple images and add a check if a image size is greater than 25mb we will resize it.
Step 1: Install the Intervention/Image Package
To get started, install the intervention/image package using Composer:
Next, add the configuration files to your application using the vendor:publish command:
Step 2: Create a View for Image Upload
Create a view file (e.g., resources/views/upload.blade.php) and add a form to upload multiple images:
Step 3: Define the Route
In your routes/web.php file, define the route for the form action:
Step 4: Implement the Controller Logic
Create a controller (e.g., ImageUploadController.php) and implement the logic to handle the image upload and resizing:
Now in our controller we will write our main business logic.
Explanation:
Validation: Ensure the request contains an array of images and validate each image's type and size.
File Handling: Check if the request has images.
Directory Creation: Create a directory with the current date if it doesn't already exist.
Image Processing: Iterate through each image, create an instance using Image::make, and check its size. If the image size exceeds 25MB, resize it to a width of 5000 pixels while maintaining the aspect ratio.
Save Image: Save the processed image to the specified directory with a unique name.
Return Response: Return a success message if the images are uploaded successfully or an error message if an exception occurs.