How to Convert Images to WebP in Laravel

How to Convert Images to WebP in Laravel

WebP is a modern image format developed by Google that provides better compression for images on the web. By converting images to WebP, you can significantly reduce file sizes, leading to faster page load times and improved performance for your applications.

Why Use WebP?

  • Smaller File Sizes: WebP images are generally 25-34% smaller than JPEG or PNG images.
  • Improved Performance: Smaller images load faster, improving your site’s speed and SEO.
  • Wide Browser Support: Most modern browsers support WebP, ensuring broad compatibility.

Prerequisites

  • Laravel installed (version 8 or higher recommended)
  • GD or Imagick PHP extensions enabled
  • Basic knowledge of Laravel routes, controllers, and requests

Step 1: Install Intervention Image

Intervention Image is a powerful PHP image manipulation library that simplifies image handling in Laravel.

Run the following command to install it:

PHPCopy
composer require intervention/image

Next, publish the configuration file by running:

PHPCopy
php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"

Step 2: Create an Image Conversion Service

Create a new service class to handle the image conversion.

PHPCopy
namespace App\Services;

use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class ImageConversionService
{
    public function convertToWebp($imagePath, $outputPath, $quality = 80)
    {
        $image = Image::make($imagePath);
        $image->encode('webp', $quality);
        Storage::put($outputPath, $image);
        return $outputPath;
    }
}

Step 3: Create a Controller

Generate a controller to handle image uploads and conversion.

PHPCopy
php artisan make:controller ImageController

Now, update the controller with the following code:

PHPCopy
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\ImageConversionService;

class ImageController extends Controller
{
    protected $imageService;

    public function __construct(ImageConversionService $imageService)
    {
        $this->imageService = $imageService;
    }

    public function uploadAndConvert(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $image = $request->file('image');
        $path = $image->store('images/original');

        $outputPath = 'images/webp/' . pathinfo($path, PATHINFO_FILENAME) . '.webp';

        $this->imageService->convertToWebp(storage_path('app/' . $path), $outputPath);

        return response()->json(['success' => true, 'path' => $outputPath]);
    }
}

Step 4: Define Routes

Open the web.php file and define the route for uploading images.

PHPCopy
use App\Http\Controllers\ImageController;

Route::post('/upload', [ImageController::class, 'uploadAndConvert']);

Step 5: Testing the Endpoint

You can now test the image upload and conversion by making a POST request to /upload with an image file. If successful, the image will be converted to WebP and saved in the specified directory.

Conclusion

By integrating WebP image conversion in your Laravel application, you can enhance performance and optimize user experience. This setup automates the process, ensuring that images uploaded to your application are optimized for the web.