Laravel 12 – How to Resize Images Using Intervention Image.

Touseef Afridi
22 Jan 26

Laravel 12 – How to Resize Images Using Intervention Image.

In this tutorial, we will learn how to resize images in Laravel 12 using the Intervention Image package, including uploading, resizing while keeping aspect ratio, and downloading images with a clean responsive form.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through adding image resizing functionality to a Laravel 12 application using the Intervention Image package. Starting with a fresh Laravel project, the package is installed and configured to handle image processing tasks such as resizing while maintaining the original aspect ratio. An ImageController is created to validate uploaded images, resize them to a specific width, and return them as downloadable files. Finally, a simple and responsive form is added to the welcome.blade.php view, making it easy for users to upload images and retrieve the resized versions without any technical knowledge.

Step # 1 : Set up a Laravel 12 application.

To get started with Laravel 12, you’ll need a working application. You can either create a new project or continue with an existing one. If the Laravel Installer is already installed, creating a new project is quick. Run the following command to generate a project named resize-image.
laravel new resize-image
If the Laravel Installer isn’t available globally, you can use Composer instead.
composer create-project laravel/laravel --prefer-dist resize-image
When creating the project through Composer, Laravel automatically sets up a minimal project structure. When using the Laravel Installer, you’ll be asked a few configuration questions. Choose the following options to proceed.
  • Starter Kit: Select none, since no authentication or frontend scaffolding is required for this project.
  • Testing Framework: Choose Pest to keep the testing setup modern and lightweight.
  • Database: Select MySQL as the primary database for the application.
  • Run Migrations: Choose yes so Laravel runs the default database migrations automatically.
  • Frontend Dependencies: Select yes to allow Laravel to install the necessary frontend packages during setup.

Once the setup is complete, Laravel creates the project, installs all dependencies, and runs the default migrations. Your Laravel 12 application is now ready for development.

Step # 2 : Navigate to the project directory.

Once the Laravel project has been created, move into the project’s root directory using your terminal or command prompt. For example, if you’re using Git Bash, run the following command.
cd c:xampp/htdocs/resize-image
This command switches your terminal to the Laravel project directory so you can start running framework specific commands.

Step # 3 : Install Intervention Image package.

Install the Intervention Image library in your Laravel application using Composer.
composer require intervention/image-Laravel
Intervention Image makes image handling in Laravel simple by providing tools for resizing, cropping, rotating, watermarking, and applying filters.

Step # 4 : Publish Intervention Image configuration.

To fully integrate Intervention Image, run the following command to publish its configuration file.
php artisan vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"
This generates an image.php file in your project’s config directory, where you can adjust settings like the image processing driver. By default, GD is used, but you can switch to Imagick if it’s installed for better performance and additional features.

Step # 5 : Create ImageController.

Create the ImageController by running the Artisan command.
php artisan make:controller ImageController
After creating the controller, replace the content of ImageController.php with the following 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 resizeImage method in the ImageController handles the image upload process. It first validates that the uploaded file is an image (JPG, JPEG, PNG) and does not exceed 2MB. Once validated, it uses Intervention Image to read the file and resize it to a width of 300 pixels while maintaining the aspect ratio. Finally, it generates a new filename for the resized image and returns it as a downloadable file with the correct content type and headers.

Step # 6 : Define route.

Import the ImageController at the top of routes/web.php.
use App\Http\Controllers\ImageController;
Then add the route for image resizing. The GET route for '/' (homepage) is already present by default in Laravel, so you only need to add the POST route.
Route::get('/', function () {
    return view('welcome');
});
Route::post('/resize-image', [ImageController::class, 'resizeImage']);
The POST route handles the form submission, processes the uploaded image via the resizeImage method, and returns the resized image to the user.

Step # 7 : Update the Welcome View.

Now let’s update the Welcome view so users can upload an image. We’ll replace the content of resources/views/welcome.blade.php with the following code.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 12 - Code Shotcut Resize Image</title>
    <!-- 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-gray-800 shadow-xl rounded-xl w-full max-w-3xl p-10 border border-gray-700">
            <h2 class="text-3xl font-semibold text-center mb-8 text-white">Code Shotcut - Resize Image</h2>
            <!-- Image Upload 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-200 mb-2">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-3 bg-gray-700 text-white border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <button type="submit"
                        class="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400">
                        Resize Image (Width: 300px)
                    </button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>
This view provides users with a simple and responsive interface for uploading and resizing images. It uses Tailwind CSS for a clean, modern design, supports JPEG and PNG files, and the submit button triggers the resizeImage method in the controller to process the uploaded image.

Step # 8 : It's time to test.

Start the Laravel development server by running.
php artisan serve
Then open your browser and go to: http://127.0.0.1:8000.

Upload an image using the form. The application will automatically resize it to the specified width while keeping the original aspect ratio intact. This ensures the image’s proportions are preserved, preventing distortion, and makes it perfect for use as profile pictures, product images, thumbnails, or any other scenario where resized images are needed.

Conclusion

By following this guide, you can easily integrate image resizing functionality into your Laravel 12 application. With the Intervention Image package, users can upload images, have them resized while maintaining their original aspect ratio, and download the processed files directly. This setup can also be extended to handle more advanced tasks such as cropping, rotating, or applying filters, making it suitable for projects like e-commerce platforms, content management systems, or any application that requires dynamic image handling.
For additional features and configuration options, refer to the Intervention Image package documentation.

Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering