How to Convert an Image to Webp in Laravel - TechvBlogs

How to Convert an Image to Webp in Laravel

Elevate your Laravel image optimization with a step-by-step guide on converting images to WebP format. Unlock the power of efficient web performance and sharper visuals through this insightful tutorial.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

4 months ago

TechvBlogs - Google News

This concise article illustrates how to convert an image to WebP format in Laravel. You will learn the process of converting images, specifically converting PNG to WebP and converting JPG to WebP, in Laravel. The following is a step-by-step explanation along with a basic example demonstrating how to convert JPG to WebP in Laravel.

In this illustration, we will showcase how to utilize the intervention/image Composer package to convert images in JPEG and PNG formats into the WebP format. This conversion is advantageous as the WebP format is optimized to improve the loading speed of web pages, leading to faster load times for website visitors.

To accomplish this conversion, we'll utilize the ImageManagerStatic class, a component of the intervention/image package. This class streamlines the process of converting images to the WebP format.

Now, let's explore a clear and concise example of the code, breaking it down step by step for a better understanding.

You can utilize this example with Laravel versions 6, 7, 8, 9, and 10.

Step 1: Install Laravel

While this step is optional, if you haven't created the Laravel app yet, feel free to proceed by executing the following command:

composer create-project laravel/laravel example-app

Step 2: Install intervention/image Package

Here, we will install the intervention/image Composer package to utilize image functions and convert images to the WebP format. Let's run the following command:

composer require intervention/image

Step 3: Create a Controller for Converting an Image to Webp

In this step, we will create a new ImageController. In this file, we will add two methods: index() for rendering the view and store() for handling the image conversion logic.

Let's create the ImageController using the following command:

php artisan make:controller ImageController

Next, let's update the code in 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

Furthermore, open the routes/web.php file and add the routes to manage GET and POST requests for rendering the view and handling the image conversion logic.

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, we need to create the imageUpload.blade.php file. In this file, we will create a form with a file input button. Copy the code below and place it in that file.

resources/views/imageUpload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Convert an Image to webp in Laravel - TechvBlogs.com</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>How to Convert an Image to webp in Laravel - TechvBlogs.com</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 the necessary steps have been completed. Now, type the command below and hit enter to run the Laravel app:

php artisan serve

Now, open your web browser, enter the provided URL, and view the output of the app:

http://localhost:8000/word-to-pdf

Thank you! If you have any more questions or if there's anything else I can assist you with, feel free to let me know.

Comments (0)

Comment


Note: All Input Fields are required.