Laravel 8 Image Resize & Upload with Intervention Image

Last updated on: by Digamber

Laravel 8 intervention image resize tutorial; This step-by-step tutorial helps you learn how to upload an image and resize an image in the laravel application with the help of the PHP intervention image package.

Ideally, image resize is the process of changing the dimension of the image; we daily browse a variety of sites, be it social media, ecommerce, or any other site where we require to upload images; sometimes, we have to create or generate thumbnail images.

Consequently, to lower down the size and the dimension of the image, we have to create the file resizing feature.

In this guide, we will tell you how to profoundly resize an image in laravel application using PHP intervention image package, this package allows you to mange the image ratio.

Laravel 8 Image Resize with Intervention Image Example

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

Install Laravel App

Let us begin the tutorial by installing a new laravel application; if you have already created the project, then skip this step.

composer create-project --prefer-dist laravel/laravel laravel-demo

Head over to app’s root:

cd laravel-demo

Add Intervention Image Package

This step describes how to install PHP intervention image package into the laravel application, type command in the terminal, and execute to install the plugin.

composer require intervention/image

Register Image Intervention Package

In order to use the image intervention package in laravel, you make sure to inject the package classes into the providers and aliases arrays.

Open the config/app.php file and update the following code in the file.

<?php

return [

	......

	$providers => [

		......,

		'Intervention\Image\ImageServiceProvider'

	],

	$aliases => [

		......,

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

	]

]

Configure Controller

In the further step, you have to execute the following command to create the new controller file; in this file, we will write the logic to handle the file upload and resize feature.

php artisan make:controller ResizeController

The index() function renders the blade view template into the view. In contrast, the resizeImage() function validates the image, sets max file upload limit, store the large image in uploads, and small and resized image in the thumbnail folder.

You also need to create two folders into the main public folder to store images and thumbnail. Similarly, create public/uploads and public/thumbnail directories.

Further, update the given code in the app/Http/Controllers/ResizeController.php file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Image;

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

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

        $image = $request->file('file');
        $input['file'] = time().'.'.$image->getClientOriginalExtension();
        
        $destinationPath = public_path('/thumbnail');

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

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

        $destinationPath = public_path('/uploads');
        $image->move($destinationPath, $input['file']);

        return back()
        	->with('success','Image has successfully uploaded.')
        	->with('fileName',$input['file']);
    }

}

Add Routes

Furthermore, open routes/web.php file and add the routes to manage GET and POST requests for image resizing.

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/file-resize', [ResizeController::class, 'index']);

Route::post('/resize-file', [ResizeController::class, 'resizeImage'])->name('resizeImage');

Set Up Blade View

Let us set up a blade view for managing file resize and uploads; we may use the default welcome blade template file. In this file, we will add Bootstrap CSS, then create a basic file upload component using bootstrap.

Open the resources/views/welcome.blade.php file and add the given below code inside the file.

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

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

    <title>Laravel Image Resize Example</title>
</head>

<body>
    <div class="container mt-5" style="max-width: 550px">
        <h2 class="mb-5">Laravel Image Resize Example</h2>     

        <form action="{{route('resizeImage')}}" method="post" enctype="multipart/form-data">
            @csrf
            @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <strong>{{ $message }}</strong>
            </div>


            <div class="col-md-12 mb-3">
                <strong>Grayscale Image:</strong><br/>
                <img src="/uploads/{{ Session::get('fileName') }}" width="550px" />
            </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="custom-file">
                <input type="file" name="file" class="custom-file-input" id="chooseFile">
                <label class="custom-file-label" for="chooseFile">Select file</label>
            </div>

            <button type="submit" name="submit" class="btn btn-outline-danger btn-block mt-4">
                Upload
            </button>
        </form>
    </div>
</body>

</html>

Run Laravel Project

We have completed the development of the image resize feature; now, its time to test the functionality. Use the following command to run the application.

php artisan serve

Type the given url on the browser to run the app.

http://127.0.0.1:8000/file-resize

Laravel resize image before upload

Conclusion

The Upload and resize an image in Laravel tutorial is ended; in this example, we explained how to create a laravel app from scratch.

How to create a controller and routes, add an intervention image package, and use its API to resize the image and display the image preview.

We hope you liked this tutorial and surely share it with others.

Digamber

I am Digamber, a full-stack developer and fitness enthusiast. I crafted this site to bestow my coding experience and love to write on JavaScript, React, Angular, Vue, Laravel.