Using and Converting the WebP Image Format in your Laravel Project

Arie Visser • October 20, 2023

laravel php

What is the WebP format?

WebP is a modern image format for the web that is developed by Google. It is based on the VP8 video format, and provides superior compression.

Because of these qualities, it is intended to replace the JPEG, PNG, and GIF formats.

According to the report on Can I use , it is supported by all mordern browsers, and more than 95% of web users are able to view the WebP format.

If you want to read more about the image format and the compression algorithm, you can view this article on web.dev.

When you are a web developer that just wants to know how to convert your images to the WebP format and integrate it in your project, please continue.

Convert images to WebP

To convert JPEG, PNG or TIFF images to the WebP format, Google created command line tools. You can download them on Google for Developers, or when you are on MacOS, you can install it with Homebrew:

brew install webp

You now have access to the cwebp and dwebp commands to compress and decompress images to and from the WebP format.

For example to convert an PNG image to WebP, you can run this shell command:

cwebp input.png -o output.webp

There are many options. Some very important argument is the quality (-q) flag, which is the compression factor. This can be a number between 0 and 100 and is 75 by default. The higher the number, the higher the quality.

To improve the quality, you could run:

cwebp -q 100 my-image.png -o my-image.webp

For al options, please review the official documentation

Convert multiple files to WebP

It is also possible to convert multiple files to WebP at once. For example, to convert all PNG files in the current folder to WebP, you can run this command:

for p in *.png; do cwebp ${p} -o "${p%.png}.webp"; done

Add support for older browsers

As mentioned earlier, more than 95% of the users are running a browser that supports WebP. However, for the remaining part, you can set a fallback image by using the picture element:

<picture>
  <source type="image/webp" srcset=“images/my-image.webp">
  <source type="image/jpeg" srcset=“images/my-image.jpg">
  <img src=“images/my-image.jpg" alt="The Description">
</picture>

Convert file uploads to WebP with PHP / Laravel

In many cases, images will be uploaded by your users that are not in the WebP format. In that case you would have to convert the images on the server. When using PHP, there are many options to create these conversions.

$image = new Imagick();
$image->readImage($input);

$image->setImageFormat('webp');
$image->setImageCompressionQuality(100);
$image->writeImage($output);
use Spatie\Image\Manipulations;
...
$this->addMediaConversion('webp-format')
    ->format(Manipulations::FORMAT_WEBP)
...

I hope this article contains all the information to use the WebP format in your Laravel project. Please let me know if you miss something or if anything can be improved.