Laravel 8 Convert Original Image to Grayscale Image

Last updated on by Digamber

Laravel 8 generate grayscale image tutorial; In this tutorial you will learn how to turn an image into a greyscale version in laravel app with the help of PHP image intervention package and that too from the scratch.

The PHP image intervention package is exorbitantly helpful for image manipulation, and it offers numerous features to handle image-related tasks. We will use image intervention’s greyscale() method for making a grayscale image from the original image in the laravel 8 app not just that it works with version 8 but also compatible for backward versions such as laravel 7, and laravel 6.

A grayscale or image is one in which the value of each pixel is a single sample representing only an amount of light; that is, it carries only intensity information. Grayscale images, a kind of black-and-white or gray monochrome, are composed exclusively of shades of gray.
– Wikipedia

Laravel 8 Grayscale Image Conversion Example

  • Step 1: Create Laravel Project
  • Step 2: Install Image Intervention Package
  • Step 3: Register Image Intervention Package
  • Step 4: Create and Set Up Controller
  • Step 5: Create Routes
  • Step 6: Create Blade View
  • Step 7: Start Development Server

Create Laravel Project

If you don’t know how to install the laravel app, type the following command on the terminal and invoke it to install a new laravel app.

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

Install Image Intervention Package

This step explains how to install the intervention image package in the laravel application, execute the following command from the command prompt.

composer require intervention/image

Register Image Intervention Package

In this step, we have to register the image intervention package, open the config/app.php file and add the given properties in providers and aliases arrays.

<?php

return [

	......
	......

	$provides => [

		.......

		......,

		......,

		'Intervention\Image\ImageServiceProvider'

	],

	$aliases => [

		......

		......,

		......,

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

	]

]

Create and Set Up Controller

Next, you have to execute the following command to generate the new FileController; in this controller, we will conjugate the code logic to generate a grayscale image.

php artisan make:controller FileController

Now, open and update the suggested code in the app/Http/Controllers/FileController.php file.

<?php

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

class FileController extends Controller
{

    public function index()
    {
    	return view('welcome');
    }

    public function imgToGreyscale(Request $request)
    {
        $input = $request->all();

        $this->validate($request, [
              'file' => 'required|image|mimes:jpg,jpeg,png,gif,svg|max:2048',
          ]);
  
          $image = $input['file'];
          $input['file'] = time().'.'.$image->getClientOriginalExtension();
          $img = Image::make($image->getRealPath());
          $img->greyscale()->save(public_path('/uploads').'/'.$input['file']);
  
          return redirect()->back()->with('success','Grayscale file uploaded.')->with('image', $input['file']);
    }
}

Create Routes

We need to define two routes, one for loading blade view template another for generating grayscale image through the POST request, open and update code in routes/web.php file.

<?php

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

/*
|--------------------------------------------------------------------------
| 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', [FileController::class, 'index']);

Route::post('/upload-file', [FileController::class, 'imgToGreyscale'])->name('generateGrayscaleImg');

Create Blade View

In this final step, we will create the blade view file, and we are not creating any new view file. Rather, we are using the default welcome.blade.php file.

So open the resources/views/welcome.blade.php file and place the following 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</title>
</head>

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

        <form action="{{route('generateGrayscaleImg')}}" 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('image') }}" 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>

We created a basic file upload element and pass the POST method, converting the original image to a grayscale image and upload into the public/uploads folder.

You require to create the uploads folder inside the public folder; here, you can see the grayscale version of the original images.

Start Development Server

In the final step, we have to start the laravel development server. Make sure to get to the terminal screen, simultaneously type the command to start the laravel app.

php artisan serve

Type the following url on the browser to test the app.

http://127.0.0.1:8000/file

Laravel grayscale image

Conclusion

Ultimately, the laravel grayscale image conversion tutorial is ended. This tutorial explained how to effortlessly make a grayscale image from the original image in the laravel application using an image intervention package. Apart from grayscale conversion, there are other APIs offered by the image intervention plugin, allowing you to resize, filter, adjust the gamma, height, opacity, and other factors.