How to Convert Any Image to Webp in Laravel

  Mar 2024
  ITSolutionsGuides
  Category: Laravel
How to Convert Any Image to Webp in Laravel

Welcome To ITSolutionsGuides,


In the realm of Laravel development we need to know how to Convert Any Image to Webp, particularly when optimizing images for web usage, the integration of the Intervention/Image package proves indispensable. To embark on converting any image to the efficient WebP format within Laravel, the utilization of Intervention/Image becomes paramount. Begin by ensuring the package is installed within your Laravel application via Composer. Subsequently, leverage its solutions, seamlessly integrated within Laravel, to convert images to WebP format with ease. Whether it's PNGs or JPGs, Intervention/Image empowers developers to effortlessly handle the conversion process. Through its intuitive API, developers can swiftly execute conversions, ensuring optimal image quality and reduced file sizes for enhanced web performance. This process entails invoking Intervention/Image's methods within Laravel controllers or service classes, manipulating images and converting them to WebP format effortlessly. By harnessing the capabilities of Intervention/Image within Laravel, developers can elevate their web projects by delivering faster-loading, more optimized images, thus enhancing user experience and site performance. Whether you're a seasoned Laravel developer or just delving into the realm of web optimization, the integration of Intervention/Image for converting images to WebP format stands as a testament to the power of Laravel's extensibility and the robust capabilities of third-party packages like Intervention/Image in the Laravel ecosystem.
To convert images to WebP format in laravel first, integrate Intervention/Image into your Laravel project via Composer. Then, utilize its solutions to effortlessly convert PNG or JPG images to WebP format using it solutions guides.

Let's Start Coding

Lets install the intervention/image package using the following command, using this package we will convert any format image to the webp file format using the intervention/image package classes.

composer require intervention/image

Let's Create Controller

Lets create the controller using the following artisan command, for detailed explanation about Creating the Controller

php artisan make:controller ImageController

we will use ImageManagerStatic::make()->encode() class from the package intervention/image to convert the images to webp format and then rename the image to add the .webp extension to the image.


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);
    }
}

Let's Create the Routes

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');
});

Let's Create Blade Files

Create the blade file using the artisan command


resources/views/imageUpload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Convert Any Image 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>How to Convert Any Image 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>

Let's Run the Application

Lets run the laravel application using the following artisan command,

php artisan serve

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides