Search

Laravel 8 Image Resize and Upload with Intervention Image

post-title

Uploading high size images in blog application is not good idea as it consumes more memory and space. Also it slows the webpage loading and ultimately affects on user experience. So it is always good idea to resize and upload images unless application requires high resolution images.

You can handle images frontside using Javascript or serverside with required extension. For Laravel web application, you can easily do it using Intervention image package. Intervention is image handling library and it provides ServiceProviders and Facades for easy Laravel integration.

Requirements

Make sure below requirements Intervention Image needed to work correctly.

PHP >= 5.4
Fileinfo Extension

And one of the following image libraries.

GD Library (>=2.0) … or …
Imagick PHP extension (>=6.5.7)

In this article we will learn resize images and upload in Laravel 8. So lets start!

Getting started

Fron your Terminal, create fresh Laravel application using composer command.

composer create-project laravel/laravel intervention

Go to application folder

cd intervention

Install and register package

Now install Intervention image package using composer command

composer require intervention/image

Add the below line in $providers array of config/app.php file

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

In the same file, add below lines in $aliases array 

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

Add routes, views and controllers

Register new routes in routes/web.php file.

<?php

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

Route::get('/intervention', [InterventionController::class, 'index'])->name('index');
Route::post('/intervention', [InterventionController::class, 'store'])->name('store');


To handle these routes, create controller.

php artisan make:controller InterventionController

This will add new controller file at app/Http/Controllers/InterventionController.php. Now open controller file and add methods.

<?php

namespace App\Http\Controllers;

use File;
use Image;
use Illuminate\Http\Request;

class InterventionController extends Controller
{
    /**
     * Show the image upload view
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('intervention');
    }

    /**
     * store image
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpg,jpeg,png,gif,svg',
        ]);

        $request_image = $request->file('image');
        $image = Image::make($request_image);
        
        $image_path = public_path('/images/');
        
        if (!File::exists($image_path)) {
            File::makeDirectory($image_path);
        }

        $image_name = time().'.'.$request_image->getClientOriginalExtension();

        // keep ratio height and width
        $image->resize(null, 200, function($constraint) {
            $constraint->aspectRatio();
        });

        $image->save($image_path.$image_name);

        return back()->with('success', 'Image uploaded successfully.');
    }
}

To upload image, create view file at /resource/views/intervention.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Intervention image upload</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row mt-5">
            <div class="col-md-12">
                <form method="post" action="{{ route('store') }}" enctype="multipart/form-data">
                    @csrf
                    <div class="mb-3">
                        <label for="image" class="form-label">Upload image</label>
                        <input class="form-control" type="file" id="image" name="image">
                    </div>
                    @error('image')
                        <div class="alert alert-danger">{{ $message }}</div>
                    @enderror
                    @if(\Session::has('success'))
                        <div class="alert alert-success">{{ \Session::get('success') }}</div>
                    @endif
                    <div class="mb-3">
                        <input type="submit" class="btn btn-primary">
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

Now run the Laravel server.

php artisan serve

Open your browser and open localhost.

http://localhost:8000/intervention

Upload file and submit the button. Your file will be saved to public/images/167911123.jpg. The file height will be 200px and auth width to aspect ratio. Visit official website to get more configurations.