DEV Community

Cover image for Convert images to WebP
Nazareno Pesado
Nazareno Pesado

Posted on

Convert images to WebP

When you try to optimize the front-end of you website you realized that PageSpeed from Google suggests to use WebP images because, as they say, are 26% smaller in size.

I'm going to teach you how to use Spatie Media Library, an awesome PHP + Laravel library to achieve this.

Let's start

1. Install Spatie Media Library

2. Prepare your model

3. Associate a file to your model

4. Converting your images

This step could be confusing because in the documentation doesn't specify how to achieve the proper conversion to WebP (or another format you need).

The first thing you have to do is to add a method called registerMediaConversions to your model. Look at this example:

class Course extends Model implements HasMedia
    use InteractsWithMedia;

    public function registerMediaConversions(Media $media = null): void
Enter fullscreen mode Exit fullscreen mode

Important things

Calling to

Enter fullscreen mode Exit fullscreen mode

we define the name of the conversion that we are going to need later to get the image.

Enter fullscreen mode Exit fullscreen mode

is the method that makes the magic of conversion to WebP (or to another format)

We include

Enter fullscreen mode Exit fullscreen mode

to perform the conversion without queue it.

Retrieve the image

So after the conversion we need to retrieve the image to use it in the front-end.

$urlToFirstImage = $course->getFirstMediaUrl('images', 'cover');
Enter fullscreen mode Exit fullscreen mode

The first parameter we define the collection where we retrieve the image.
Te second parameter we specify the conversion name we defined before.

So in that simple way we can convert an image to WebP using Spatie Media Library.

Please refer to the library documentation to expand the usage and adjust this to your specific needs.

Top comments (0)