Share this article:

Blog
Apr 06, 20228 min read

Drupal 9 convert image to WebP format

Vasil Boychev

Area Manager – Benelux

Drupal 9 convert image to WebP format

What is WebP and what are it's advantages?

For a long time, JPG has been placed as a standard for image data on the web. However, in 2013, Google (together with a group of other open source developers) were able to develop WebP, a new picture encoder technique that intended to compress images smaller than JPG while maintaining image quality.

WebP is a contemporary image format for the web that offers greater lossless compression. Webmasters and web developers can use WebP to create smaller, richer images that load faster on the web.

When compared to PNGs, WebP lossless images are 26% smaller. At the same SSIM quality index, WebP lossy images are 25-34 percent smaller than equivalent JPEG images.

Transparency is supported by lossless WebP at a cost of only 22 percent more data. When lossy RGB compression is acceptable, lossy WebP also offers transparency, resulting in file sizes that are typically three times less than PNG.

Read Frequently Asked Questions about WebP.

How to implement WebP format for all the images on a Drupal 9 website?

There are 3 main steps to follow:
  1. Configure server webp format support.
  2. Install and configure Imagemagick and WebP Drupal modules.
  3. Add “Convert to WEBP” effect to relevant image styles.

1. Configure server WebP format support.

We need to make sure we have the server WebP support. For our purpose we can use two different php extensions, imagick and gd. They both support converting images to WebPformat. The difference is only in configurations in next steps. First we will cover the gd extension and after that we will look at imagick.

GD extension:
First you need to check your php.ini file. You must find:

extension=php_gd2.dll

or

xtension=php_gd.dll.

And after that restart your server to apply changes. If you can`t find this extension in your php.ini file, you need to add it to your environment.

It will look like this:

sudo apt-get update
sudo apt-get install php-gd

GD extension: DDEV environment you need to configure DDEV Hook. You can set hook post start adding additional settings in .ddev/config.yaml.

hooks:
post-start:

- exec: sudo apt-get update
- exec: sudo apt-get install php-gd

By using hooks you’re able to run linux commands into the DDEV environment.

If you’ve done these steps described in this section correctly, you will see a new block in phpinfo().

It will look like this:

This section will show you that the gd extension was installed successfully. You need to check here, if WebP support is enabled.

GD

Imagick:
Imagick is another library that you can use for image manipulations. The installation imagick is pretty much based on what we saw in the previous section.

sudo apt-get update
sudo apt-get install php-imagick

Or DDEV example:

hooks:
post-start:

- exec: sudo apt-get update
- exec: sudo apt-get install php-imagick

You can check if imagick is installed successfully by using the command below

php -m | grep imagick

After the last manipulation you will need to restart your web server, most probably apache.

If all done the right way, you will see something like:

imagick

Note:

In the sections that are described above, you need to check if WEBP Support is enabled for PHP. If you can’t find WebP support or format listed in the previous section you’ll need to install it manually via this command:

sudo apt-get update
sudo apt-get install -y webp

And again – restart your web server.

2. Install and configure Imagemagick and WebP Drupal modules.

So far so good, we already have a configured environment. I hope you completed the previous step without any problems. If not – please repeat!

Next we will look at two modules that we will need to install and configure to set image converting.

Good, let's proceed to installing the two modules we need. First one – Imagemagick.

composer require drupal/imagemagick

drush en imagemagick -y

And the second one – WebP.

composer require drupal/webp

drush en webp -y

After installing and enabling all modules run drush cr, to rebuild cache.

The WebP module provides the WEBP converter extension in the image style effects, which we’ll show a bit further. No configurations needed for the WebP module. We will configure the ImageMagick module instead.

The ImageMagick module has two ways of configuring. We will cover both in this section. In the previous section you chose some php library for image manipulation gd/imagick, at this point you will need to configure imagemagick module accordingly you choose.

First we will look at imagick configuration steps:

Navigate to: /admin/config/media/image-toolkit

If you choose the Imagick library you will need to choose the first option ImageMagick image toolkit. Also you need to set image quality.

Image quality option will reduce image quality to percent that you choose. Note that if you reduce the quality of the image too much the image will not look good. You will need to play around with this.

You also need to set a path to imagiMagick bin folder that will use module to convert images. You can download the extension based on your operating system. After that extract all from this folder in preferred location on your server. And enter the path to bin folder in image toolkit field “Path to the package executable” and that’s all.

image toolkit page

In the next step we need to set image formats that we will use. Note that you can enable or disable image formats that you want to use.

image formats page

Now let's look at how to configure imagemagick with GD2 extension:

If you choose gd processor for manipulation with images, you need only to set “GD2 image manipulation toolkit" in image toolkit options.

image toolkit settings

Don't forget to run drush cr after applying module settings to rebuild drupal cache.

3. Add “Convert to WEBP” effect to relevant image styles.

Okay, we already have WebP support on our server, now we need to set up converting images to WebP format by adding converters in all image styles.

Open : /admin/config/media/image-styles, And create a new image style.
 

image styles

And enter a name, for example “Image process”.

image style naming

And click Create new style.

In this new image style we need to create a converter for our images.

Select convert from dropdown and click add.

image style name

On the next page select WebP option from dropdown and click Add effect. The already installed WebP module gives us the WEBP extension here:

convert an image between extensions

If you want to apply the new effect to any existing image styles – use the same approach.

Bonus: Apply newly created image style in Twig

At this point we need to understand the WebP format will be applied only for images that use an image style. For all other cases we’d need to apply image style manually in the code. For example – in twig. Most probably the images implemented there don’t use any image style. Fortunately enough, we’re able to apply a particular image style directly in Twig.

To catch images that we added in style like background or in twig template we need to set image style using image_style() twig function using the ‘image_process’ image style we’ve created before. Please note that we must seed the image style machine name in the image_style() function.

To find the machine name of your image style that we already created you need to open image style in the Drupal 9 admin panel and look at the url.

You will see something like:

The last argument in url is the your image style machine name that you can use as a parameter to image_style().

style machine name

If we want to add image style in css in twig background it would look like:

background-image: url({{'public://image_folder/image.jpg' | image_style('image_process')}});

To get images folder you need to use public:// variable that represents the public files destination, usually it’s ‘sites/default/files’.

Or if you want to add image style to twig field uri, it would look like:

background-image: url('{{ file_url(content.field_image.0['#media'].field_media_image.entity.fileuri | image_style('image_process')) }}');

Note:

If you want to use this with a twig media field, you would need to get media field uri.

In Conclusion

WebP is able to take data compression to a new level thanks to the inclusion of a prediction mode to the JPG process, making it clear to see how it can outperform its JPG-based relative. And we have the results to prove it

Before

before image size

After

after image size

Before

before performance result

After
after performance result

SUBSCRIBE TO OUR NEWSLETTER

Share this article:

SUBSCRIBE TO OUR NEWSLETTER

Related Blog Articles

    Why startups hesitate to work with a bespoke software development agency – and how we address every concern

    Blog

    Why startups hesitate to work with a bespoke software development agency – and how we address every concern

    Startups often hesitate to work with software agencies due to concerns over cost, control, and flexibility. Discover how Bulcode’s bespoke software solutions address each challenge, ensuring growth and agility.

    Written by Svetoslava Angelova
    Nov 05, 20245 min read
    Building a high-performing Agile team: Our proven approach

    Blog

    Building a high-performing Agile team: Our proven approach

    Discover how we build high-performing Agile teams by defining clear roles, fostering collaboration, and using flexible tools.

    Written by Svetoslava Angelova
    Aug 27, 20248 min read
    Drupal 11: What to expect? Comprehensive guide to new features and enhancements

    Blog

    Drupal 11: What to expect? Comprehensive guide to new features and enhancements

    Drupal 11 is out! In this article, discover it's exciting features and improvements. Upgrade now to redefine your digital strategy with Bulcode's expert support.

    Written by Svetoslava Angelova
    Aug 05, 20247 min read
    Single Directory Components in Drupal core: A comprehensive overview

    Blog

    Single Directory Components in Drupal core: A comprehensive overview

    Explore how Single Directory Components (SDC) in Drupal Core streamline the development process by encapsulating component-related files into a single directory. Learn about the benefits of SDCs and follow a step-by-step guide to implement them in your Drupal projects.

    Written by Nikolay Tsekov
    Aug 07, 20244 min read
    Config split module tutorial for Drupal

    Blog

    Config split module tutorial for Drupal

    Very often we as developers need to work with different environments. This could sometimes lead to (un)expected problems. In Drupal 8 we use the configuration system which works pretty nice, but there are cases where the settings for the local and any other environment should be different.

    Written by Ivaylo Tsandev
    May 20, 20217 min read
    Unveiling the power duo: Next.js as the Headless frontend of Drupal 10

    Blog

    Unveiling the power duo: Next.js as the Headless frontend of Drupal 10

    Discover the dynamic synergy between Drupal 10 and Next.js, as this powerful combination reshapes the landscape of web development. Next.js, an open-source React-based framework, is seamlessly integrated as the headless frontend of Drupal 10, offering a plethora of benefits. From enhanced performance with features like automatic code splitting and server-side rendering to flexible design and SEO-friendly capabilities, this collaboration empowers developers to create high-performing, scalable, and visually appealing web applications. The efficient content management of Drupal 10 coupled with Next.js' adaptability to trends ensures a cutting-edge development approach, positioning this tandem at the forefront of modern web development practices. Embrace the future with the Drupal 10 and Next.js combination, redefining how we approach and craft dynamic online experiences.

    Written by Todor Kolev
    Feb 07, 20245 min read
    Config ignore module tutorial for Drupal

    Blog

    Config ignore module tutorial for Drupal

    Sometimes we don't want our configurations to be shared in the codebase. So what can we do in such cases?

    Written by Ivaylo Tsandev
    Jul 27, 20217 min read
    How we optimised an SSL overall rating from B to A+

    Blog

    How we optimised an SSL overall rating from B to A+

    Optimising the SSL implementation allows all customers to open and browse the site securely without warnings.

    Written by Mihail Shahov
    Feb 15, 20223 min read
    Understand Drupal versions and plan a migration strategy

    Blog

    Understand Drupal versions and plan a migration strategy

    Recognise the various Drupal versions and keep your website up-to-date.

    Written by Svetoslava Angelova
    Mar 21, 20224 min read
    React overview - Definition, SPA, Components, Hooks

    Blog

    React overview - Definition, SPA, Components, Hooks

    React is a free and open-source front-end JavaScript framework for creating user interfaces based on UI components. It is also known as React.js or ReactJS.

    Written by Mihail Shahov
    May 13, 20226 min read
    What is Agile and why we use it?

    Blog

    What is Agile and why we use it?

    Agile is a time-boxed, iterative method to software delivery that aims to provide software gradually throughout the project rather than all at once near the end.

    Written by Svetoslava Angelova
    Sep 15, 20225 min read
    NVM vs NPM vs Yarn

    Blog

    NVM vs NPM vs Yarn

    Compared to the three technologies, NVM differs from the other two. Node Version Manager (NVM) is used to manage Node.js versions. NPM and Yarn are Node.js package managers. They allow downloading, installing, and managing packages when developing in JavaScript.

    Written by Ventsislav Venkov
    Sep 15, 20225 min read

    GET IN TOUCH

    Have a project you'd like to launch?