Laravel 11 - Resize Images with Intervention Image
Laravel 11 - Resize Images with Intervention Image
In this tutorial, we are going to discuss how to resize images in Laravel 11. We will cover the step-by-step process to resize and download images efficiently using simple methods.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
This guide helps you add image resizing functionality to a Laravel application using the Intervention Image package, a powerful image manipulation library. After setting up a fresh Laravel project, the package is installed and configured to handle various image processing tasks such as resizing, cropping, and more. An ImageController is created to manage image uploads, validate the uploaded files, and resize the images while maintaining their aspect ratio, ensuring high-quality results. Once resized, the image can be downloaded directly from the browser as a new file. The final step includes adding a user-friendly, clean, and responsive form to the view, making it easy for users to upload images, adjust their size, and retrieve the resized version without needing technical knowledge.
Step # 1 : Create fresh Laravel project or use an existing one.
If Laravel is installed globally, create a new project named resize-image using the command.
laravel new resize-image
Or
If you don't have Laravel globally installed, you can use Composer to create a new Laravel project using the following command.
composer create-project laravel/laravel --prefer-dist resize-image
After running one of the above commands, you'll be prompted.
- Would you like to install the starter kit? — Select none.
- Select the testing framework. — Choose Pest.
- Select the database for your application. — Choose mysql.
- Run the default database migration? — Select yes.
Step # 2 : Access the project directory.
Navigate to your Laravel project’s root directory where your application is installed. You can use a terminal or command prompt for this. Here's an example of how to do it using Git Bash.
cd c:xampp/htdocs/resize-image
Step # 3 : Install the Intervention Image package.
Run the following Composer command to install the package.
composer require intervention/image-Laravel
Intervention Image provides an easy-to-use image manipulation library that supports resizing, cropping, watermarking, rotating images, and applying various filters, making it a versatile tool for handling image processing in Laravel projects.
Step # 4 : Publish the configuration.
To fully integrate the Intervention Image package into your Laravel application, you need to publish its configuration file. This is done by running the following command
php artisan vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"
Running this command will generate an image.php file inside the config directory of your Laravel project. This configuration file allows you to customize various settings for the image manipulation process, including the choice of image processing drivers such as GD or Imagick. By default, the package uses GD, but you can switch to Imagick if it's installed on your server for potentially better performance or more advanced features.
Step # 5 : Create a controller
Generate the ImageController using Artisan.
php artisan make:controller ImageController
Once the controller is created, Replace the content of ImageController.php with the below code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Intervention\Image\Laravel\Facades\Image;
class ImageController extends Controller
{
public function resizeImage(Request $request)
{
// Validate the uploaded file
$request->validate([
'image' => 'required|image|mimes:jpg,jpeg,png|max:2048',
]);
// Read the uploaded image
$image = Image::read($request->file('image'));
// Resize while maintaining aspect ratio
$resizedImage = $image->scale(width: 300);
// Generate a new filename for download
$filename = 'resized_' . $request->file('image')->getClientOriginalName();
// Return the resized image as a downloadable file
return response($resizedImage->encode())
->header('Content-Type', $request->file('image')->getMimeType())
->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
}
}
The ImageController is responsible for handling the image upload process in the Laravel application. It first validates the uploaded file, ensuring it's an image of specific formats (JPG, JPEG, PNG) and within a size limit of 2MB. Once the image is validated, it uses the Intervention Image package to read and manipulate the image. The scale() method is used to resize the image while maintaining its aspect ratio, setting the width to 300 pixels. The controller then generates a new filename for the resized image and returns it as a downloadable file with the appropriate content type and headers.
Step # 6 : Define a route.
Import the ImageController class in routes/web.php.
use App\Http\Controllers\ImageController;
Add routes for the homepage and image resizing.
Route::get('/', function () {
return view('welcome');
});
Route::post('/resize-image', [ImageController::class, 'resizeImage']);
The GET route is responsible for loading the homepage where users can access the image upload form, while the POST route handles the form submission, processes the uploaded image, resizes it to the desired dimensions, and returns the modified image to the user.
Step # 7 : Update the view.
Modify the resources/views/welcome.blade.php file to include an image upload form that enables users to select and submit images for resizing, providing a seamless and user-friendly experience for image manipulation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Shotcut - Resize Image</title>
<!-- Link to Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 text-white">
<div class="min-h-screen flex items-center justify-center">
<div class="bg-white shadow-lg rounded-lg w-full max-w-3xl p-8">
<h2 class="text-3xl font-semibold text-center mb-6 text-gray-900">Code Shotcut - Resize Image</h2>
<!-- Form -->
<form action="{{ url('/resize-image') }}" method="POST" enctype="multipart/form-data" class="space-y-6">
@csrf
<div>
<label for="image" class="block text-lg font-medium text-gray-900">Select an image to resize</label>
<input type="file" name="image" id="image" accept="image/png, image/jpeg" required
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50 text-gray-900">
</div>
<div>
<button type="submit"
class="w-full bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500">
Resize Image (Width: 300px)
</button>
</div>
</form>
</div>
</div>
</body>
</html>
This view provides a simple and responsive user interface for uploading images and resizing them. It uses Tailwind CSS for styling, ensuring a clean and modern design. The form accepts JPEG and PNG image files, with a single input field for image selection and a submit button that triggers the resizing process.
Step # 8 : It's time to test.
Start the Laravel development server.
php artisan serve
Open a browser and visit.
127.0.0.1:8000
Upload an image, and it will be automatically resized to the specified dimensions while preserving its original aspect ratio. This ensures that the image's proportions are maintained, preventing distortion while adjusting its size, making it suitable for various use cases such as profile pictures, product images, or thumbnails.
Conclusion
By following this guide, you can easily integrate image resizing functionality into your Laravel application. The Intervention Image package simplifies image manipulation, and this setup allows users to upload images, resize them, and download the processed versions. This solution can be further extended for more complex tasks such as cropping, rotating, or applying filters, which can be useful for various types of applications, including content management systems and e-commerce platforms.
For more details and advanced features, refer to the package documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments