Laravel

Laravel 12 Resize Image Before Upload With Example

Introduction

Handling images efficiently is crucial for any web application. Large images can slow down your website, increasing load time and affecting user experience. That’s where image resizing comes in. If you’re working with Laravel 12 and want to resize images before uploading, you’re in the right place. In this guide, (Laravel 12 Resize Image Before Upload) we’ll walk through the step-by-step process of resizing images in Laravel 12 using the Intervention Image package.

Let’s dive in!

Step 1: Install Laravel 12

First, make sure you have Laravel 12 installed. If not, you can create a new Laravel project using the following command:

composer create-project laravel/laravel ImageResizeApp

Once installed, navigate to your project directory:

cd ImageResizeApp

Step 2: Install the Intervention Image Package

Laravel does not have built-in image manipulation functions, so we need to install Intervention Image, a popular package for image processing. Run the following command:

composer require intervention/image

Next, add the service provider in config/app.php (this step is optional for Laravel 12 as it supports auto-discovery).

'providers' => [
    Intervention\Image\ImageServiceProvider::class,
],

'aliases' => [
    'Image' => Intervention\Image\Facades\Image::class,
],

Now, publish the configuration file:

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"

Step 3: Create the Image Upload Controller

Run the following command to generate a new controller:

php artisan make:controller ImageUploadController

Now, open app/Http/Controllers/ImageUploadController.php and modify the store method to handle image resizing before uploading.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class ImageUploadController extends Controller
{
    public function store(Request $request)
    {
        // Validate the uploaded file
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        // Handle the uploaded image
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $filename = time() . '.' . $image->getClientOriginalExtension();

            // Resize the image
            $resizedImage = Image::make($image)->resize(300, 300)->encode();

            // Store the resized image in the storage folder
            Storage::disk('public')->put('uploads/' . $filename, $resizedImage);

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

        return back()->with('error', 'Image upload failed!');
    }
}

Step 4: Create the Image Upload Form

Now, let’s create a simple form to upload images. Open resources/views/image-upload.blade.php and add 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 Image Upload</title>
</head>
<body>

    <h2>Upload and Resize Image in Laravel 12</h2>

    @if(session('success'))
        <p>{{ session('success') }}</p>
    @endif

    @if(session('error'))
        <p>{{ session('error') }}</p>
    @endif

    <form action="{{ route('image.upload') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <label>Select an image:</label>
        <input type="file" name="image" required>
        <button type="submit">Upload</button>
    </form>

</body>
</html>

Step 5: Define Routes

Open routes/web.php and add the following routes:

use App\Http\Controllers\ImageUploadController;

Route::get('/upload-image', function () {
    return view('image-upload');
});

Route::post('/upload-image', [ImageUploadController::class, 'store'])->name('image.upload');

Step 6: Configure Storage

Ensure the storage folder is linked to the public directory so that the images can be accessed:

php artisan storage:link

Step 7: Run the Application

Finally, start the Laravel development server:

php artisan serve

Visit http://127.0.0.1:8000/upload-image, select an image, and upload it. Your image will be resized to 300×300 pixels before being saved.

Resizing images before uploading is an essential feature for any web application dealing with media files. Using Laravel 12 and the Intervention Image package, you can easily optimize images, improve performance, and enhance user experience.

If you are looking for professional Laravel development services, CodeHunger provides top-notch web solutions tailored to your needs.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button