Laravel Image Optimization using Spatie

By | October 1, 2019

Hello Coders !! This tutorial is about the Laravel image optimization using spatie laravel package.

Suppose you are dealing with large scale projects that have a very large amount of images at that time this package integration will help you.

At that time image optimization becomes a very important part of whole site benefits in terms of site size, site speed and page load time.

In this tutorial, you will see how to integrate and use this image optimization package.

Step 1 : Install Laravel

Follow our previous article for install a fresh laravel

Here is the link: Laravel setup

After successfully installation of a fresh laravel follow these steps

Step 2 : Install Spatie’s package

Install laravel image optimizer package by running below command in terminal

composer require spatie/laravel-image-optimizer

This command will install spatie package.

Step 3: Package Configuration

Now we will configure the package for that we will open the file config/app.php and set the service provider and aliases shown as below.

'providers' => [
	....
	Spatie\LaravelImageOptimizer\ImageOptimizerServiceProvider::class,
],
'aliases' => [
	....
	'ImageOptimizer' => Spatie\LaravelImageOptimizer\ImageOptimizerFacade::class,
],

After adding this we will run below command in our terminal and this will publish the package.

Now you just open the file named config/image-optimizer.php.

Here in this file, you can change any configuration based on your project.

The file will look like this.

<?php

use Spatie\ImageOptimizer\Optimizers\Svgo;
use Spatie\ImageOptimizer\Optimizers\Cwebp;
use Spatie\ImageOptimizer\Optimizers\Optipng;
use Spatie\ImageOptimizer\Optimizers\Gifsicle;
use Spatie\ImageOptimizer\Optimizers\Pngquant;
use Spatie\ImageOptimizer\Optimizers\Jpegoptim;

return [
    /*
     * When calling `optimize` the package will automatically determine which optimizers
     * should run for the given image.
     */
    'optimizers' => [

        Jpegoptim::class => [
            '-m85', // set maximum quality to 85%
            '--strip-all',  // this strips out all text information such as comments and EXIF data
            '--all-progressive',  // this will make sure the resulting image is a progressive one
        ],

        Pngquant::class => [
            '--force', // required parameter for this package
        ],

        Optipng::class => [
            '-i0', // this will result in a non-interlaced, progressive scanned image
            '-o2',  // this set the optimization level to two (multiple IDAT compression trials)
            '-quiet', // required parameter for this package
        ],

        Svgo::class => [
            '--disable=cleanupIDs', // disabling because it is know to cause troubles
        ],

        Gifsicle::class => [
            '-b', // required parameter for this package
            '-O3', // this produces the slowest but best results
        ],

        Cwebp::class => [
            '-m 6', // for the slowest compression method in order to get the best compression.
            '-pass 10', // for maximizing the amount of analysis pass.
            '-mt', // multithreading for some speed improvements.
            '-q 90', // quality factor that brings the least noticeable changes.
        ],
    ],

    /*
    * The directory where your binaries are stored.
    * Only use this when you binaries are not accessible in the global environment.
    */
    'binary_path' => '',

    /*
     * The maximum time in seconds each optimizer is allowed to run separately.
     */
    'timeout' => 60,

    /*
     * If set to `true` all output of the optimizer binaries will be appended to the default log.
     * You can also set this to a class that implements `Psr\Log\LoggerInterface`.
     */
    'log_optimizer_activity' => false,
];

Step 4 : Add Middleware

Spatie’s package laravel-image-optimizer itself is providing its own middleware and to use that just open this file app/Http/Kernel.php and add middleware in it.

protected $routeMiddleware = [
   	...
   	'optimizeImages' => \Spatie\LaravelImageOptimizer\Middlewares\OptimizeImages::class,
];

Step : 5 Create Route

Here we will create a route for image optimize post request in routes/web.php file.

Route::post('/imageUpoad', 'ImageController@store')
    ->middleware('imageOptimize');

Step : 6 Create Controller File

Let’s create an ImageController file by running this command in terminal.

php artisan make:controller ImageController

This command will create a controller file in your App\Http\Controllers folder.

Now, Create a store function in this file. It will look like this after adding a store function.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageController extends Controller
{
    public function store() {
        $this->validate(request(), [
            'photo' => 'required|image:jpeg '
        ]);

        request()->photo->storeAs('images', 'optimized.jpg');

        /Session::put('success', 'Your Image Successfully Optimize')

        return redirect()->back();
    }
}

Step 7 : Create View File

Now, We will open a welcome.blade.php file from resources/views folder and edit it. After edit code will look like this.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @auth
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ route('login') }}">Login</a>

                        @if (Route::has('register'))
                            <a href="{{ route('register') }}">Register</a>
                        @endif
                    @endauth
                </div>
            @endif

            <div class="content">
                <div class="title m-b-md">
                    @if($message = Session::get('success'))
                    <div class="alert alert-info alert-dismissible fade in" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                        <strong>Success!</strong> {{ $message }}
                    </div>
                    @endif
                    <form action="{{ route('imageOptimize') }}" enctype="multipart/form-data" method="POST">
                        {{ csrf_field() }}
                        <div class="form-group">
                            <label for="">Image</label>
                            <input class="form-control" name="image" type="file" />
                            <button type="submit">Upload</button>
                        </div>
                    </form>
                </div>

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

From here you can change code as per your requirement. Please visit this GITHUB package for assistance Spatie Package.

Leave a Reply

Your email address will not be published. Required fields are marked *