Laravel 9 Grayscale Image Conversion Tutorial Example

Have you ever wondered how to convert a true colour image to a grayscale image? If your answer is no, probably this Laravel RGB image to Grayscale image conversion tutorial is specifically for you.

This quick guide will explain every bit of information on how to transform the original Image to a grayscale image in Laravel using the PHP intervention image library.

Intervention Image is a quintessential open-source PHP image handling and manipulation library.

It offers tons of pre-cooked methods for image editing in PHP based application; with it, you can create, edit, and compose images just like that.

Laravel 9 Upload Image and Grayscale Conversion Example

  • Step 1: Install Laravel App
  • Step 2: Add Intervention Image Library
  • Step 3: Setting Up Controller
  • Step 4: Register New Routes
  • Step 5: Build Blade View in CI
  • Step 6: Run CI Application

Install Laravel App

In the first step, open the command prompt, run the below command to generate a new laravel project.

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

Move toward the project’s root.

cd laravel-canary

Add Intervention Image Library

Now that app has been installed; add the PHP intervention image library in our Laravel app. Moreover, update this package after installation in the app.php configuration file.

composer require intervention/image

To register the Intervention Image plugin, update the config/app.php.

return [
	......

	$provides => [

		'Intervention\Image\ImageServiceProvider'

	],

	$aliases => [

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

	]

]

Setting Up Controller

In this section, you need to take care of two tasks, create a controller and create functions in the controller to load the file upload widget in view and process the grayscale conversion in laravel.

php artisan make:controller FileUploadController

Add code in app/Http/Controllers/FileUploadController.php.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Image;

class FileUploadController extends Controller
{
    public function index()
    {
    	return view('profile');
    }

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

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

Register New Routes

Let’s register two new controllers to handle the grayscale conversion; one route will evoke the view, and another process the image manipulation.

Add code in routes/web.php.

<?php

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


Route::get('/convert-image-to-grayscale', [FileUploadController::class, 'index']);
Route::post('/convert-image', [FileUploadController::class, 'store'])->name('convert.image');

Build Blade View in CI

Here are the steps that you need to follow to set up the blade for image conversion in laravel:

  • Create profile.blade.php file
  • Add bootstrap 5 CSS link at the header part
  • Create basic file upload form using bootstrap 5
  • Set the action with the post request url.

Add code in resources/views/profile.blade.php.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>Laravel Convert Original Image to Grayscale Example</title>

    <style>
       .container { 
           max-width: 700px
        }
    </style>
</head>

<body>
    <div class="container mt-4">
        <form action="{{route('convert.image')}}" method="post" enctype="multipart/form-data">
            @csrf
            @if ($message = Session::get('success'))
            <div class="alert alert-warning">
                <strong>{{ $message }}</strong>
            </div>


            <div class="col-md-12 mb-2">
                <img src="/uploads/{{ Session::get('file') }}" />
            </div>
            @endif

            @if (count($errors) > 0)
            <div class="alert alert-info">
                <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">Choose file</label>
            </div>

            <button type="submit" name="submit" class="btn btn-dark">
                Submit
            </button>
        </form>

    </div>

</body>

</html>

Run CI Application

Next, given below command help you run the laravel app, also use the provided url to run the app in the browser.

php artisan serve
http://127.0.0.1:8000/convert-image-to-grayscale

Change image to grayscale in laravel

Conclusion

We hit the road with downloading a new laravel app, keeping the primary task laravel grayscale image conversion task in mind.

Throughout the journey, we relied on the PHP Intervention image plugin. We opened the doorway of gratification and learned how to manipulate the Image in the Laravel application.

After following every bit of instruction, we managed to convert the original Image to a Grayscale Image in Laravel, and I hope this guide helped you.