img-1

Laravel Image Optimizer: Optimize Images Of Your Laravel Website with RabbitLoader  

With the help of a laravel image optimizer, you can speed up your website by optimizing the image file. 

Adding images is essential to making your website more aesthetically pleasing. However, adding too many unoptimized images can slow down your website’s loading time. According to LoadNinja, images account for 64% of the overall page’s size, which can severely impact the loading speed of your Laravel website.

Way too many website owners struggle with the slow loading speed of their Laravel websites due to the rampant use of unoptimized images. 

Chances are you are using similar issues too. Here we will discuss how to manually optimize images on the Laravel website using an image optimizer & we would also see how you can do it yourself using your coding skills without an image optimizer

Laravel Image Optimizer

However, manually optimizing an image can be challenging if you are not from a technical background. 

A Laravel image optimizer can make this process easier. There are several Laravel image optimizers available online that can help you optimize images on your website. However, investing time in the wrong laravel image optimizer can waste your valuable as well as money.

Hence, before investing in a laravel image optimizer, first, you need to know the effectiveness of the laravel image optimizer. 

Here, we will explore, as a Laravel image optimizer, how RabbitLoader optimizes your images on the Laravel website and helps you speed up the website. 

But before diving into the solution, first, we will talk about the importance of image optimization, the most common reason behind a slow laravel website and mention a few freely available tools to measure your laravel website’s performance. 

Why Should You Optimize Images In Laravel Website 

When it comes to a website’s PageSpeed optimization, the first thing that pops up in almost every website owner’s mind is “image optimization.” Now, you may wonder if this is really fruitful for optimizing Laravel performance. 

Document

Get The Best PageSpeed Score

For Your WordPress Website

All in One Optimization Plugin
No Coding Knowledge Required

Let’s explain the importance of image optimization, which includes:

  • Reduce the total page file size
  • Speed up the page loading time 
  • Improve the mobile experience 

Reduce The Total Page File Size

The total page file size indicates the summation of each resource file’s size of a webpage, such as HTML, CSS, JavaScript files and media (image, video, and map) files. Among the resource files, images consume the most space and thus are mostly responsible for increasing the page loading time. 

Optimizing images can significantly improve the page loading time by reducing the total page file size of a website. Image optimization is more effective if your website has a lot of images. 

Reduce page file size

Let’s understand with an example.

Assume a particular page on your website has 10 images of 500kb each. The total image file size will be 5 MB, increasing the webpage’s page load time. By optimizing the images, you can reduce the image file size, which can reduce the total page file size. Hence, the website’s page loading performance would be improved greatly. 

Speed Up The Page Loading Time 

A website’s loading creates the first impression of your website in the user’s mind. An unoptimized image can typically increase the page loading time of a Laravel website, which can negatively affect the user experience and increase the bounce rate, harming the conversion rate. According to the envisage digital website, a one-second delay in the page loading time can reduce the conversion rate by 7%. 

speed up page loading time

By optimizing the image of the website, you can improve its page loading performance, which would in turn would enhance the user experience. Users are more likely to engage with your Laravel website’s content, increasing the on-page time and reducing the bounce rate. Hence, you may reach your goal by achieving a good conversion rate. 

Improve The Mobile Experience 

Another key benefit of image optimization is making your website more mobile-friendly. This is essential to ensuring the business’s consistent conversion rate and good ranking in any search engine. 

Improve Mobile experience

According to Think with Google, if the page loading time is increased by 10 seconds from 1 second, the bounce rate will be increased by 123% for the mobile version of the website. 

By optimizing images, you can make your Laravel-based website more mobile-friendly and provide a better user experience to your mobile users.  

The Most Common Reason Behind A Slow Laravel Website

If you know the reason behind a slow Laravel website, you can plan your efforts to optimize the loading speed of your website. Here, we will discuss the most common reasons behind a slow Laravel website, which includes the following:  

  • Using unoptimized images
  • Not deferring the non-critical images
  • Not serving the images from CDN caching

Using unoptimized images

As mentioned earlier, using too many unoptimized images can increase the total page file size of a Laravel website, which can slow down the page loading time of that website.  

Not deferring the non-critical images 

Images that are not present above the fold are also known as non-critical images. These non-critical images do not need to load during the initial page load. 

Document

Get The Best PageSpeed Score

For Your WordPress Website

All in One Optimization Plugin
No Coding Knowledge Required

Hence, if you do not defer them, your website’s page loading time can increase. Below, in this blog post, we have discussed how you can defer the non-critical images.

Not serving the images from CDN caching

A CDN cache reduces the network latency caused by the long physical distance between the user and the origin server. If you are not using CDN cache, then the resource file will be directly retrieved from the origin server. 

If the distance between the server and the user is high, then it will take more time to load the resource file. This can slow down the page loading time of a Laravel website. 

Tools to Measure Your Laravel Website’s Performance

If you are curious about your website’s performance, here are freely available tools to measure it. 

  1. Google PageSpeed Insights
  2. GTMetrix 
  3. RabbitLoader

Google PageSpeed Insights

When it comes to measuring the PageSpeed performance of any website, the first tool that comes to mind is Google PageSpeed Insights(PSI). Google developed this PageSpeed analyze tool to measure the website’s performance based on both lab data as well as field data. 

Google PageSpeed Insights scores webpages on a scale of 0 to 100 based on the Core Web Vitals metrics (a set of performance metrics developed by Google). It also provides suggestions on how to improve PageSpeed performance.  

Pagespeed Insights Score

Just enter our domain name on Google PSI and click on “Analyze” to see your home page’s PageSpeed score. Along with the PageSpeed score, you can also see the Core Web Vitals Assessment results. 

For better understanding, Google also categorizes the PageSpeed score based on threshold values. If your Laravel website’s PageSpeed score is 90 or above, then the website’s PageSpeed performance is good; no further optimization is needed.

However, if the PageSpeed performance score is more than 50 but doesn’t exceed 90, then it needs to be improved to be in a green zone. A below-50 PageSpeed score of your website indicates that the website fails the test in Google PageSpeed Insights

GTMetrix 

GTMetrix is the best alternative to Google PageSpeed Insights for monitoring a website’s PageSpeed performance. This online PageSpeed monitoring tool allows you to customize your PageSpeed test by choosing the location, network and browser type. 

GT Metrix Score

GTmetrix grades your website’s PageSpeed performance on a scale of A to F. You can also see the core web vitals performance here. In the premium version of GTmetrix, you can see the PageSpeed performance of each page of your Laravel website. 

How To Optimize Images In Laravel Website Manually 

Optimizing images can improve the website’s PageSpeed performance. But how do we optimize images?

Optimizing images manually involves a multitude of technicalities, which can be daunting for a non-technical person. However, with the help of a laravel image optimizer like RabbitLoader SDK, you can easily optimize the images in Laravel. We will discuss this in the next section. 

Here, we will mainly concentrate on how to optimize images on the Laravel website manually. 

  1. Compress the image file 
  2. Implement lazy loading
  3. Serve the images from CDN

How To Compress The Image File Manually In A Laravel Website? 

Image compression reduces the size of an image file. There are two types of image compression methods: lossy compression and lossless compression. 

Compress Images

While lossy compression slightly reduces the visual quality of the image, lossless compression reduces the image file size without losing the image quality. Image compression is one of the most effective image optimization techniques. 

Let’s discuss how to do image compression on your Laravel website. 

  • Step 1: In order to compress the images in the Laravel website, first, create a laravel project by following the below syntax:

composer create-project –prefer-dist laravel/laravel image-compress-project

  • Step 2: Install an image compressor package by following the below syntax:

composer requires spatie/image-optimizer 

Here we are using spatie/image-optimizer Image compression package. If you want to use another package, just change the package name in the above syntax. 

  • Step 2: After installing the image compressor package, to optimize the images, install the following tools: JpegOptim, Pngquant 2, optipng, SVGO 1, Gifsicle, and cwebp. Here we are showing you how to install these tools on different platforms. 

For Ubuntu:

sudo apt-get install jpegoptim

sudo apt-get install pngquant

sudo apt-get install optipng

sudo npm install -g [email protected]

sudo apt-get install gifsicle

sudo apt-get install webp

For MacOS:

brew install jpegoptim

brew install pngquant

brew install optipng

npm install -g [email protected]

brew install gifsicle

brew install webp

  • Step 3: Now make a controller to make the logic for image compression. 

php artisan make: controller Compress_Controller

Compress_Controller is the class. You can modify the class name. 

  • Step 4: After creating the class, you need to create methods. You can paste the code below. 

use Exception;

Illuminate\Http\Request;

Illuminate\Support\Facades\Validator;

Spatie\ImageOptimizer\OptimizerChainFactory;

 //Extend the controller class

class Compress_Controller extends Controller

{

    public function index()

    {

                    // entry point of the program which shows the image optimizer view

        return view(‘image-optimizer’);

    }

    public function compress(Request $request)

    {

       // Check the image formats and upload size(Here, we will provide the max size Max  upto 5MB….. You can can the max size according your needs)

$validator = Validator::make(

            $request->all(),

            [

                'image' => 'required|file|mimes: jpeg,jpg,png,gif,svg,webp|max:5120',

            ]

        );

        if($validator->fails()){

            return redirect()->back()->withErrors($validator->errors())->withInput();

        }

        try{

            // Get the uploaded image from the request

            $image = $request->file('image');

            // Make a unique filename for the uploaded image

            $imagename = time().'.'.$image->getClientOriginalExtension();

            // Set the path to save the original image

            $imagepath = public_path('/images/');

            // Set the path to save the compressed image

            $pathToOutput = public_path('/optimizedImage/');

            // Save the original image

            $image->move($imagepath, $imagename);

            // Compress the image and save it to the optimizedImage path using Spatie's OptimizerChainFactory 

            $optimizerChain = OptimizerChainFactory::create();

            $optimizerChain->optimize($imagepath.$imagename,$pathToOutput.$imagename);

            // Delete the original image

            unlink($imagepath.$imagename);

            // Redirect back to the image uploader with the success message.

            return back()->with('success', 'successfully compressed the image.');

        }

        catch(Exception $e)

        {

            // Redirect back to the image uploader with an error message.

            $error = 'Opps! something goes wrong. Please try later’;

            return redirect()->back()->with('error',$error)->withInput();

        }

    }

}

    

  • Step 5: Now, to upload the images, create a form in the  image-optimizer.blade.php file and paste the code below. 
<div class="container" style="margin-top: 50px;">

    @if (session('success'))

        <div class="alert alert-success">

            {{ session('success') }}

        </div>

    @endif

    <h2>Compress JPEG</h2>

    <form action="{{ url('compress') }}" method="post" enctype="multipart/form-data">

        @csrf

        <div class="form-group">

            <input type="file" name="image" class="form-control" required>

        </div>

        <button type="submit" class="btn btn-primary">Compress</button>

    </form>

</div>
  • Step 6: To show the image upload form, you need to add routes.

Route::get(‘/image-optimizer’, [ImageController::class, ‘index’]);

  • Step 7: by following the code below, compress the image and save the folder.

Route::post(‘/compress’, [ImageController::class, ‘compress’]);

  • Step 8: Finally, it’s time to run the project. 

php artisan serve

How To Implement Lazy Loading Manually In Laravel? 

Without implementing lazy loading, improving PageSpeed performance can be difficult for a website, especially when it has many images. In general, the browser loads each image during the page rendering, which can make the loading time longer. 

Implement lazy loading

Implementing lazy loading can improve page loading time by instructing the browser to load only images that are visible in the above-the-fold. Let’s see how to implement lazy loading on the Laravel website. 

Here we will explain this step by step to make the process easier. 

  • Step 1: To implement lazy loading in the Laravel website, install a package that can manipulate the image file. Here, we install the Intervention Image Package.

composer requires intervention/image 

  • Step 2: After installing the package, configure it by following the line in the aliases section of the config/app.php file. 

‘InterventionImage’ => Intervention\Image\Facades\Image::class,

  • Step 3: To store the image, create a model and, if necessary, a migration. For this use need to use two commands: make: model and make: migration.
  • Step 4: add an extra colum for creating the image path. For this, you can use the syntax:

$table->string(‘image’);

  • Step 5:  Now, create a form by following the syntax:
<form action="/upload" method="POST" enctype="multipart/form-data">

    @csrf

    <input type="file" name="image">

    <button type="submit">Upload</button>

</form>
  • Step 6: Add a controller to handle the image upload and store the image path in the database. 
use Intervention\Image\Facades\Image;

public function upload(Request $request)

{

    $image_Path = $request->file('image')->store('images');

    //Save the image path to the database using your model

    YourModel::create([

        'image' => $image_Path,

    ]);

    return redirect()->back();

}

 

  • Step 7: Here, you need to add a lazy loading attribute in the HTML file. 
<img src="{{ asset('path-to-placeholder-image') }}" data-src="{{ asset($model->image) }}" alt="" loading="lazy">

<script src="{{ mix('js/app.js') }}"></script>

<script>

    document.addEventListener("DOMContentLoaded", function() {

        const lazyImages = document.querySelectorAll('img[loading="lazy"]');

        const imageObserver = new IntersectionObserver(function(entries, observer) {

            entries.forEach(function(entry) {

                if (entry.isIntersecting) {

                    const lazyImage = entry.target;

                    lazyImage.src = lazyImage.dataset.src;

                    lazyImage.onload = function() {

                        lazyImage.removeAttribute("data-src");

                        lazyImage.removeAttribute("loading");

                    };

                    observer.unobserve(lazyImage);

                }

            });

        });

        lazyImages.forEach(function(lazyImage) {

            imageObserver.observe(lazyImage);

        });

    });

</script>

Please keep in mind that you need to replace the path-to-placeholder-image according to your image files requirement.

How To Enable CDN In Laravel Website?

As discussed earlier, using a CDN can reduce the network latency between the user and the server, which can improve the loading time of your website. Now, you may be worried about how to implement a Content Delivery Network (CDN) on the Laravel website. 

Document

Get The Best PageSpeed Score

For Your WordPress Website

All in One Optimization Plugin
No Coding Knowledge Required

Like previous image optimization strategies, you can easily implement the Content Delivery Network in your Laravel website by following the below steps. Here we are using CDNsun. 

  • Step 1: Define the Content Delivery Network in the config file by adding some line of code to your Laravel’s /config/app.php file.
<?php

return [

...

    'cdn_enabled'   => true,

/* Here we are using CDNsun. You need to modify the cdn_domain if you are using other CDN*/

    'cdn_domain'    => '12345.r.cdnsun.net',

    'cdn_protocol'  => 'https',

];
  • Step 2: Create a CDN helper file. 
<?php

function cdn($url = null)

{

    $url = (string) $url; 

    if(empty($url))

    {

        throw new Exception('URL missing');

    }

    $pattern = '|^http[s]{0,1}://|i';        

    if(preg_match($pattern, $url))

    {

        throw new Exception('Invalid URL. ' .

            'Use: /image.jpeg instead of full URI: ' .

            'https://domain.com/image.jpeg.'

        );

    }

    $pattern = '|^/|';        

    if(!preg_match($pattern, $url))

    {

        $url = '/' . $url;

    }

    if(!Config::get('app.cdn_enabled'))

    {

        return $url;

    }

    else

    {

        return Config::get('app.cdn_protocol') . '://' . Config::get('app.cdn_domain') . $url;

    }    

}
  • Step 3: Now you need to add the composer file under the autoload key. 
"autoload": {    

     ...

     "files": [

         "app/helpers.php"

     ]

},

Step 4: Finally, you need to add a CDN helper. 

{{ cdn('/image.jpg') }}

Note: Before modifying anything in the resource file, first back up all your resource files. 

Optimize A Laravel Website With RabbitLoader

You have already seen that optimizing images manually can be daunting due to its extensive technicalities. Most website owners invest a lot of money in the development team or ten different Laravel image optimizers, which may ruin the website’s PageSpeed performance by conflicting with each other. 

Optimize a laravel website with RabbitLoader

Here, RabbitLoader will provide you with a superior solution.  Let’s see how RabbitLoader optimizes the images as a Laravel image optimizer. 

  • With the help of RabbitLoader SDK, you can reduce all image file sizes without losing their original quality. It is known as lossless image compression.
  • RabbitLoader SDK converts all images into modern web formats such as WebP image format and AVIF image format to optimize images, reducing the image file size as well.  
  • Without requiring any coding knowledge, RabbitLoader implements lazy loading to defer images that are not available in the above-the-fold. 
  • RabbitLoader has an inbuilt premium Content Delivery Network (CDN). Hence, when you use the RabbitLoader SDK, it will automatically serve images from its 300+ edge servers. 
  • RabbitLoader implements an efficient browser caching mechanism to render the images quickly. 
  • RabbitLoader adds responsive images and improves the aspect ratio, making your laravel app more mobile-friendly. 

Not only as a laravel image optimizer, but you can also use RabbitLoader for Laravel performance optimization, such as minifying and compressing the resource files (HTML, CSS, and JavaScript), generating critical CSS, reducing unused CSS & JavaScript and many more. For more details, check our RabbitLoader speed-up laravel website

Thus, if you are also looking for a laravel image optimizer, don’t invest your money in the wrong laravel image optimizer. Install RabbitLoader to optimize all images and improve Laravel performance. Go through our knowledge base for installation guidance. 

Document

Get The Best PageSpeed Score

For Your WordPress Website

All in One Optimization Plugin
No Coding Knowledge Required