How to Resize Images in Laravel 8 Before Uploading to Server

Last updated on by Digamber

Throughout this tutorial, you will learn how to create resize image functionality in the Laravel 8 application.

Laravel 8 resizes the image before the upload is the primary topic that has been asked by many novice developers. Fret not; in this tutorial, we will help you understand the entire concept of laravel 8 generate thumbnail images without putting extra effort to resize and upload images in the laravel 8 project.

Laravel 8 Image Intervention example will also be explained in this step-by-step guide. You will learn to use the intervention/image package for resizing the image in laravel; this will also help you clear the doubts about resizing the image in laravel.

Intervention package follows the FIG standard PSR-2 to ensure a high level of interoperability between shared PHP code; this Image library is a powerful open-source PHP image handling and manipulation package.

It offers facile and meaningful methods to create, edit, and compose images and currently supports the two most common image processing libraries GD Library and Imagick. It allows you to control PHP image manipulating easier; not just that, you can also create image thumbnails, watermarks, or format large image files.

Create Laravel App

A brand new or existing laravel application is required to build the laravel image resize feature.

composer create-project laravel/laravel --prefer-dist laravel-image-resize-example

Install Intervention Image Library

Image resizing in Laravel application needs to have intervention/image library installed; simultaneously, it allows you to generate a thumbnail image.

composer require intervention/image

The next step is to inject intervention class altogether in providers and aliases array inside the config/app.php configuration file.

return [
    ......
    ......

    $provides => [
        ......,

        Intervention\Image\ImageServiceProvider::class

    ],

    $aliases => [
        .....,

        'Image' => Intervention\Image\Facades\Image::class

    ]

]

Create New Controller

Inside the controller file, you can create the functions to handle the image resizing in Laravel or manifesting the blade view for the file upload component.

php artisan make:controller FileController

Head over to app/Http/Controllers/FileController.php file, place the following code within:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Image;

class FileController extends Controller
{
    /**
     * Init view.
     */
    public function index()
    {
        return view('welcome');
    }
  
    /**
     * Image resize
     */
    public function imgResize(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'imgFile' => 'required|image|mimes:jpg,jpeg,png,svg,gif|max:2048',
        ]);
  
        $image = $request->file('imgFile');
        $input['imagename'] = time().'.'.$image->extension();
     
        $filePath = public_path('/thumbnails');

        $img = Image::make($image->path());
        $img->resize(110, 110, function ($const) {
            $const->aspectRatio();
        })->save($filePath.'/'.$input['imagename']);
   
        $filePath = public_path('/images');
        $image->move($filePath, $input['imagename']);
   
        return back()
            ->with('success','Image uploaded')
            ->with('fileName',$input['imagename']);
    }
}

Build Routes

To create routes you need to import the controller and add the following code in routes/web.php file:

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\FileController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
  
Route::get('/', [FileController::class, 'index']);
Route::post('/image-resize', [FileController::class, 'imgResize'])->name('img-resize');

Create Blade View

Create, or you might also use the existing welcome blade view file, afterward add the following code in resources/views/welcome.blade.php file:

Also, create images equally important thumbnails folders in the public directory.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <title>Laravel Image Resize Example</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">
</head>

<body>

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

        @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <strong>{{ $message }}</strong>
        </div>
        <div class="row">
            <div class="col-md-4">
                <h3>Primary Image:</h3>
                <img src="/images/{{ Session::get('fileName') }}" />
            </div>
            <div class="col-md-4">
                <h3>Thumbnail:</h3>
                <img src="/thumbnails/{{ Session::get('fileName') }}" />
            </div>
        </div>
        @endif

        <form action="{{ route('img-resize') }}" enctype="multipart/form-data" method="post">
            @csrf
            <div class="form-group">
                <input type="text" name="name" class="form-control" placeholder="Name">
            </div>
            <div class="form-group">
                <input type="file" name="imgFile" class="imgFile">
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-success">Save</button>
            </div>
        </form>
    </div>

</body>

</html>

At last, make sure your application is working fine, so run the command to start the project.

php artisan serve
http://localhost:8000/image-resize

Thats it for now; you have seen how to resize an image and keep it in the images and thumbnails folder.