Optimizing Image Loading Converting PNG and JPEG to WebP in Laravel

Spread the love

Hello Guys,

This article provides a comprehensive guide on converting images to the WebP in Laravel, focusing on how to efficiently transform both PNG and JPEG images. We’ll walk you through the step-by-step process of converting a PNG image to WebP and a JPEG image to WebP using the “intervention/image” Composer package.

By following this tutorial, you’ll learn how to leverage this package to optimize your web page loading speed. The WebP format’s efficiency will result in faster loading times for your website’s visitors, enhancing their overall experience.

To accomplish this conversion, we will utilize the “ImageManagerStatic” class, which is a vital component of the “intervention/image” package. This class streamlines the image conversion process to the WebP format.

Next, we’ll explore a straightforward and comprehensive code example, breaking it down step by step for enhanced clarity.

This code example is compatible with Laravel versions 6, 7, 8, 9, and 10, making it versatile for various Laravel iterations.

Example of Converting PNG and JPEG to WebP in Laravel:

Also Read: How to rename Git Branch Name with Git Command?

Step 1: Install Laravel

While this step is optional, if you haven’t yet generated your Laravel app, feel free to proceed by running the following command:

composer create-project laravel/laravel example-ap

Step 2: Install intervention/image Package

In this guide, we will demonstrate how to install the Intervention/Image Composer package, which provides a range of powerful image manipulation functions. We’ll also walk you through the process of converting images to the webp format using this composer package. To get started, simply execute the following command:

composer require intervention/image

Step 3: Create Controller

In this next step, we’ll be generating a brand-new ImageController. Within this file, we’ll introduce two essential methods, 'index()' and 'store()', to facilitate view rendering and manage image storage.

To craft your ImageController, simply execute the following command:

Also Read: How to integrate LINKEDIN LOGIN in Laravel 10

php artisan make:controller ImageController

Now, it’s time to make updates to the code within the Controller File.

app/Http/Controllers/ImageController.php
<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Intervention\Image\ImageManagerStatic;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
    
class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(): View
    {
        return view('imageUpload');
    }
        
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
        $this->validate($request, [
            'image' => ['required',
                        'image',
                        'mimes:jpg,png,jpeg,gif,svg',
                        'max:2048'],
        ]);
      
        $input = $request->all();
        $image  = ImageManagerStatic::make($request->file('image'))->encode('webp');
  
        $imageName = Str::random().'.webp';
  
        /*  
            Save Image using Storage facade
            $path = Storage::disk('public')->put('images/'. $imageName, $image);
        */
  
        $image->save(public_path('images/'. $imageName));
        $input['image_name'] = $imageName;
  
        /* 
            Store Image to Database
        */
       
        return back()
            ->with('success', 'Image Upload successful')
            ->with('imageName', $imageName);
    }
}

Step 4: Create and Add Routes

Next, navigate to your routes/web.php file and incorporate the necessary routes for handling both GET and POST requests, enabling the rendering of views and storing image data.

Also Read: How to Crop an Image Before Uploading in LARAVEL 10

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageController;
  
/* 
|--------------------------------------------------------------------------
| 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::controller(ImageController::class)->group(function(){
    Route::get('image-upload', 'index');
    Route::post('image-upload', 'store')->name('image.store');
});

Step 5: Create Blade File

In the final step, it’s essential to generate the “imageUpload.blade.php” file. Within this file, we’ll construct a form that includes a file input button. Please proceed to copy the code provided below and paste it into the aforementioned file.

resources/views/imageUpload.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Optimizing Image Loading Converting PNG and JPEG to WebP in Laravel</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    
<div class="container">
    <h1>Optimizing Image Loading Converting PNG and JPEG to WebP in Laravel</h1>
    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
           
    @if ($message = Session::get('success'))
      
    <div class="alert alert-success alert-dismissible fade show" role="alert">
      <strong>{{ $message }}</strong>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  
    <div class="row">
        <div class="col-md-4">
            <strong>Original Image:</strong>
            <br/>
            <img src="/images/{{ Session::get('imageName') }}" width="300px" />
        </div>
    </div>
    @endif
            
    <form action="{{ route('image.store') }}" method="post" enctype="multipart/form-data">
        @csrf
        <div class="row">
            <div class="col-md-12">
                <br/>
                <input type="file" name="image" class="image">
            </div>
            <div class="col-md-12">
                <br/>
                <button type="submit" class="btn btn-success">Upload Image</button>
            </div>
        </div>
    </form>
</div>
    
</body>
</html>

Run Laravel App:

All necessary steps have been completed. To run your Laravel app, simply type the following command and press “Enter“:

Also Read: How to Upload Images with Spatie Media Library in LARAVEL 10

php artisan serve

To access the app output, open your web browser and enter the provided URL.

http://localhost:8000/image-upload

We trust you’ll discover our Laravel Blogs to be a valuable resource.

Leave a Comment