How to Resize Image Before Upload in Laravel 9

What if you have to resize an image before uploading it to the server? If you are a novice laravel developer looking to create such a feature, get along with us.

Throughout this Laravel image resize tutorial, we will teach you how to generate a thumbnail or resize the image before uploading it to the server using the notable PHP intervention image package.

This Laravel image resize before upload example is incomplete without intervention image package. You can effortlessly create image thumbnails, watermarks or format large image files using Intervention Image.

Intervention Image is an agile, open-source PHP image handling and manipulation tool.

It offers tons of eloquent yet pragmatic ways to create, edit, and compose images. It comes with two profound image processing libraries like GD Library and Imagick.

Laravel 9 Intervention Image Resize Image Before Upload Example

  • Step 1: Install Laravel App
  • Step 2: Set Up Intervention Image Package
  • Step 3: Generate and Set Up Controller
  • Step 4: Register New Routes
  • Step 5: Set Up Blade View
  • Step 6: Run Laravel Project

Install Laravel App

Your first and foremost task is to install the latest version of the laravel application.

Here is the command you need to execute on the command prompt.

composer create-project --prefer-dist laravel/laravel my-laravel-app

Just after that enter into the laravel project.

cd my-laravel-app

Set Up Intervention Image Package

Intervention image can be installed in laravel but only work appropriately if you have PHP >= 5.4, Fileinfo Extension, or either GD Library (>=2.0) or Imagick PHP extension (>=6.5.7) image libraries.

composer require intervention/image

We have successfully added the intervention image library and now we have to register the package in laravel by adding the Image service provider in provides and Image Facade in aliases arrays.

Update code in config/app.php file.

return [

	......

	$provides => [

		'Intervention\Image\ImageServiceProvider'

	],

	$aliases => [

		'Image' => 'Intervention\Image\Facades\Image'

	]

]

Generate and Set Up Controller

Subsequently, go ahead and generate a new controller; in this file, we will conjugate all the methods and functions in a single class.

php artisan make:controller BlogController

Next, get into the app/Http/Controllers/BlogController.php, import the Image package, define two functions. These functions will simultaneously load the blade view template and resize the image before upload.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Image;

class BlogController extends Controller
{
    public function index()
    {
    	return view('index');
    }

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

        $img = $request->file('imgFile');
        $input['imgFile'] = time().'.'.$img->getClientOriginalExtension();
        
        $filePath = public_path('/thumbnail');

        $imgFile = Image::make($img->getRealPath());

        $imgFile->resize(150, 150, function ($constraint) {
		    $constraint->aspectRatio();
		})->save($filePath.'/'.$input['imgFile']);

        $filePath = public_path('/uploads');
        $img->move($filePath, $input['imgFile']);

        return back()
        	->with('success','Image uploaded.')
        	->with('imgFile',$input['imgFile']);
    }
}

Register New Routes

Routes set the stage for navigation, helps you make HTTP requests, so import the controller, define routes using the controller in the routes/web.php file.

<?php

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


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

Implement Feature in Blade View

In the final section of this guide, we will create a tiny file upload form using Bootstrap 5, use the route name in action to request to resize the image and display the resized thumbnail in the view.

Create index.blade.php file in the view folder, and update code in resources/views/index.blade.php file.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>Laravel Image Resize Example</title>
</head>

<body>
    <div class="container mt-4">

        <h2 class="mb-4 text-center">Laravel Resize Image Before Upload</h2>     

        <form method="post" action="{{route('upload.image')}}" enctype="multipart/form-data">
            @csrf
            @if ($message = Session::get('success'))

            <div class="alert alert-success">
                <strong>{{ $message }}</strong>
            </div>

            <div class="card mb-3">
                <div class="card-header">
                    Resized image:
                </div>
                <div class="card-body"> 
                    <img src="/thumbnail/{{ Session::get('imgFile') }}"/>
                </div>
            </div>
            @endif

            @if (count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            @endif

            <div class="mb-3">
                <input class="form-control form-control-lg" id="formFileLg" name="imgFile" type="file">
            </div>

            <div class="d-grid">
                <button type="submit" name="submit" class="btn btn-dark">Upload File</button>
            </div>
        </form>
    </div>
</body>

</html>

Start Laravel Application

Every piece of code has been placed diligently at its place, and we are left with testing only.

So, without further ado, run the given command and open the app in the browser using the provided url.

php artisan serve
http://127.0.0.1:8000/index

Resize Image Before Upload in Laravel

Conclusion

Laravel is a popular PHP framework, which gives unbound flexibility to build robust features in less time utterly. We demystify important instructions to help you learn how to resize the image before uploading it in laravel.

Moreover, we unlock the significance of the intervention image package in this laravel image resize tutorial. I hope we have been eloquent in explaining every bit of this laravel tutorial.