Laravel 12 How to Resize Images Before Uploading

Hi there! If you're building a web app with Laravel 12 and want to resize images before uploading them, you're in the right place. In this guide, I'll walk you through the process step-by-step in simple language.

We'll use the Intervention Image package to resize images and create thumbnails, making your app more efficient. Whether you're a beginner or an experienced developer, this tutorial is easy to follow.

laravel-12-how-to-resize-images-before-uploading

Step 1: Set Up Your Laravel 12 Project

If you already have a Laravel 12 project, you can skip this step. If not, let’s create a new one. Open your terminal and run:

laravel new example-app

This command sets up a fresh Laravel 12 application named "example-app." Make sure you have Composer installed on your system.

Step 2: Install the Intervention Image Package

To resize images, we’ll use the Intervention Image package, which is perfect for creating thumbnails. Run the following command in your terminal to install it:

composer require intervention/image-laravel

This package simplifies image processing and integrates seamlessly with Laravel.

Step 3: Define Routes

Next, we need to set up routes to handle the image upload form and the upload process. Open the routes/web.php file and add the following code:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;

Route::get('image-upload', [ImageController::class, 'index']);
Route::post('image-upload', [ImageController::class, 'store'])->name('image.store');

These routes point to an ImageController that we’ll create next. The index method will display the upload form, and the store method will handle the image upload and resizing.

Step 4: Create the Image Controller

Let’s create a controller to manage the image upload and resizing logic. Run this command in your terminal:

php artisan make:controller ImageController

Now, open the app/Http/Controllers/ImageController.php file and add the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Intervention\Image\Laravel\Facades\Image;

class ImageController extends Controller
{
    public function index(): View
    {
        return view('imageUpload');
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $image = $request->file('image');
        $imageName = time().'.'.$image->extension();

        // Resize and save thumbnail
        $destinationPathThumbnail = public_path('images/thumbnail');
        $img = Image::read($image->path());
        $img->resize(100, 100, function ($constraint) {
            $constraint->aspectRatio();
        })->save($destinationPathThumbnail.'/'.$imageName);

        // Save original image
        $destinationPath = public_path('images');
        $image->move($destinationPath, $imageName);

        return back()->with('success', 'Image uploaded successfully!')
                     ->with('imageName', $imageName);
    }
}

Note: Before running the app, create two folders in the public directory: images and thumbnail (inside the images folder). These will store the original and resized images.

This controller does two things:

- The index method loads the upload form.

- The store method validates the uploaded image, resizes it to 100x100 pixels while maintaining the aspect ratio, and saves both the original and thumbnail images.

Step 5: Create the View File

Now, let’s create the front-end form for uploading images. Create a file named imageUpload.blade.php in the resources/views directory and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 12 How to Resize Images Before Uploading</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
<body>
<div class="container">
    <div class="card mt-5">
        <h3 class="card-header p-3"><i class="fa fa-star"></i> Laravel 12 How to Resize Images Before Uploading</h3>
        <div class="card-body">
            @if (count($errors) > 0)
                <div class="alert alert-danger">
                    <strong>Whoops!</strong> There were some issues with your input.<br><br>
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            @session('success')
                <div class="alert alert-success" role="alert">
                    {{ $value }}
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <strong>Original Image:</strong><br/>
                        <img src="/images/{{ Session::get('imageName') }}" width="300px" />
                    </div>
                    <div class="col-md-4">
                        <strong>Thumbnail Image:</strong><br/>
                        <img src="/images/thumbnail/{{ Session::get('imageName') }}" />
                    </div>
                </div>
            @endsession

            <form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="mb-3">
                    <label class="form-label" for="inputImage">Image:</label>
                    <input
                        type="file"
                        name="image"
                        id="inputImage"
                        class="form-control @error('image') is-invalid @enderror">
                    @error('image')
                        <span class="text-danger">{{ $message }}</span>
                    @enderror
                </div>
                <div class="mb-3">
                    <button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Upload</button>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

This Blade template creates a simple form using Bootstrap for styling. It displays error messages if the upload fails and shows both the original and thumbnail images after a successful upload.

Step 6: Run the Laravel Application

You’re all set! To run your Laravel app, use this command in your terminal:

php artisan serve

Conclusion

And that’s it! You’ve successfully set up image resizing in Laravel 12 using the Intervention Image package. This feature is great for optimizing storage and improving.

By following these steps, you can make your Laravel app more efficient and user-friendly. I hope this tutorial was easy to follow and helped you add image resizing to your project.

Frequently Asked Questions (FAQs)

Q1: What image formats are supported in this tutorial?
A: The tutorial supports JPEG, PNG, JPG, GIF, and SVG formats. You can modify the validation rules in the controller to allow other formats if needed.

Q2: Can I change the thumbnail size?
A: Yes! In the ImageController.php file, update the resize(100, 100) line to your desired dimensions, like resize(200, 200).

Q3: What is the maximum file size for uploads?
A: The maximum file size is set to 2MB (2048 KB) in the validation rule. You can increase this by changing max:2048 to a higher value, but ensure your server settings (e.g., upload_max_filesize in php.ini) allow it.

Q4: Why do I need to create the images and thumbnail folders?
A: These folders store the uploaded original images and resized thumbnails. Laravel needs them to save the files in the public directory for easy access.

Q5: What if I get a “Class Image not found” error?
A: This means the Intervention Image package isn’t installed correctly. Run composer require intervention/image-laravel again and ensure the package is listed in your composer.json file.

For more detailed information, refer to the official Intervention Image.


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS