Laravel Image Processing – Intervention Image Package

0 653

In this article, we will discuss “Laravel Image Processing – Intervention Image Package”. As we know, Image processing is the most common requirement of every framework. Today, I will explain to you one of the packages “Intervention Image” which provides optional support to the Laravel framework.

Now, the question is “What is Intervention Image?”

It’s an open-source PHP image manipulation library. It provides an easier way to manipulate images. You can also use this library in any of your PHP projects. This library helps us to manage every task in an easy way using little lines pf codes possible.

Package Prerequisites

Currently, the package supports two Image processing extensions.

  • GD
  • Imagick

Make sure you have one of these installed in your PHP environment before you start the development.

Setup New Laravel Application

Use the following composer command to install a new Laravel application.

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

After that, configure the database in the .env” file.

...
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=lara_img
DB_USERNAME=root
DB_PASSWORD=
...

Next, we need to run the artisan migrate command. This will create the necessary tables in the database.

php artisan migrate

If you face the error “Access Violation 1071”. Then, check this article to fix the issue “Fix Laravel Syntax or Access Violation 1071”.

Create Table Image

Here, we need to create a table “image”. So, you can use the following artisan command to create a migration file.

php artisan make:migration create_table_images --create=images

Newly created file located at “database/migrations”. Open that file and update the up function. Add your required columns in this migration file. For example, I’m adding only one column “file”.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTableImages extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->text('file');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
}

Our migration file is ready, just execute the artisan migrate command to add those changes into your database.


Install Intervention Image Package

Go to the terminal and execute the following composer command.

composer require intervention/image

Time to update the “config/app.php”. So, open the file and update the providers and alias array.

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

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

By default, the Intervention Image uses PHP’s GD library extension to process all images. If you want to switch to Imagick, then you can pull a configuration file into your application by running the given PHP artisan command.

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

After that, the config file located at “config/image.php”. You can change this as per your requirements.


Create Routes

Here, we will add two routes in “routes/web.php”.

Route::get('/upload-image', 'UploadController@getUploadForm');
Route::post('/upload-image', 'UploadController@postUploadForm');

“get” route is redirecting a user to upload form. And, “post” route is used to process the uploading.


Create Model

You can use the following command to create a model.

php artisan make:model Images

After executing the above mention command, the model file is located at “app/Images.php”.

I’m adding fillable in the model file as per the columns in my table.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Images extends Model
{
    protected $fillable = ['file'];
}

Create Controller

Use the following Artisan command to create “UploadController”.

php artisan make:controller UploadController

After that, a newly created controller located at “app/Http/Controllers”. Open the file and add the following code into the “UploadController”.

<?php

namespace App\Http\Controllers;

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

class UploadController extends Controller
{
    public $imagesPath = '';
    public $thumbnailPath = '';
 
    /**
     * Upload form
     */
    public function getUploadForm()
    {
        $images = Images::get();
        return view('upload-image', compact('images'));
    }

    /**
     * @function CreateDirectory
     * create required directory if not exist and set permissions
     */
    public function createDirecrotory()
    {
        $paths = [
            'image_path' => public_path('images/'),
            'thumbnail_path' => public_path('images/thumbs/')
        ];

        foreach ($paths as $key => $path) {
            if(!File::isDirectory($path)){
                File::makeDirectory($path, 0777, true, true);
            }
        }

        $this->imagesPath = $paths['image_path'];
        $this->thumbnailPath = $paths['thumbnail_path'];
    }

    /**
     * Post upload form
     */
    public function postUploadForm(Request $request)
    {
        $request->validate([
            'upload.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
        ]);

        if($request->hasFile('upload')) {

            $this->createDirecrotory();

            foreach ($request->upload as $file) {

                $image = Image::make($file);
                // you can also use the original name
                $imageName = time().'-'.$file->getClientOriginalName();

                // save original image
                $image->save($this->imagesPath.$imageName);

                // resize and save thumbnail
                $image->resize(150,150);
                $image->save($this->thumbnailPath.$imageName); 
        
                $upload = new Images();
                $upload->file = $imageName;
                $upload->save();
        
            }

            return back()->with('success', 'Your images has been successfully Upload.');
        }
    }
}

Create Blade Template

Creating a blade template “upload-image.blade.php” in the “resources/views” directory, which contains the HTML form.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 7 - Image Upload Example</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <style>
        .wrap {
            padding: 30px 0;
        }
        h2 {
            margin-bottom: 30px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-sm-12">

                <div class="wrap">

                    <h2>Laravel Multiple Image Upload with Intervention Images Package Example</h2>

                    @if ($message = Session::get('success'))
                        <div class="alert alert-success alert-block">
                            <button type="button" class="close" data-dismiss="alert">×</button>
                            <strong>{{ $message }}</strong>
                        </div>
                    @endif
            
                    @if(is_countable($images) && count($images) > 0)
                        <div class="row">
                            <div class="col-md-8">
                                <strong>Original Image:</strong>
                            </div>
                            <div class="col-md-4">
                                <strong>Thumbnail Image:</strong>
                            </div>
                            @foreach($images as $img)
                                <div class="col-md-8">
                                    <img src="/images/{{$img->file}}" style="width:400px" />
                                </div>
                                <div class="col-md-4">
                                    <img src="/images/thumbs/{{$img->file}}"  />
                                </div>
                            @endforeach
                        </div>
                    @endif

                    @if (count($errors) > 0)
                        <div class="alert alert-danger">
                            <strong>Whoops!</strong> There were some problems with your file.
                            <ul>
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <form action="{{ URL::to('/upload-image') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="row">
                            <div class="col-md-6">
                            <input type="file" name="upload[]" multiple>
                            </div>
                            <div class="col-md-6">
                                <button type="submit" class="btn btn-info">Upload</button>
                            </div>
                        </div>
                    </form>

                </div>

            </div>
        </div>    
    </div>
</body>
</html>

Testing

Use the Artisan serve command to run the Laravel application.

php artisan serve

This will start the Laravel Development Server, After that, you can use “http://127.0.0.1:8000/” in your browser to access your application. This will show you the simple form, after that whenever we upload any image. Then the result looks like:

Laravel Image Processing - Intervention Image Package


Final Word’s

I hope you have enjoyed this tutorial, Today we’ve explored  “Laravel Image Processing – Intervention Image Package”. If you have any query then please feel free to add in the comment section 🙂

Keep Learning, Stay Safe 🙂


You may like:

Handling File Upload in Laravel

Multiple File Upload in Laravel

Laravel Logging Guzzle Requests in File

How to Log All SQL Queries in Laravel

Leave A Reply

Your email address will not be published.