Boosting Sitecore XP Performance with WebP Images

Boosting Sitecore XP Performance with WebP Images

  • 03/08/2023
  • Technical
  • Coding, Sitecore XP, Third-party Integrations, Best Practices, Code Examples

In the rapidly evolving digital landscape, web performance is no longer just a nice-to-have, it's a necessity. As user expectations rise, the demand for faster load times becomes paramount. One pivotal factor in website speed is image size and format. Here's where WebP comes into play, offering superior lossless and lossy compression for web images. And guess what? You can integrate WebP into your Sitecore XP. Let's walk through it step-by-step.

WebP: A Brief Introduction

Developed by Google, WebP is a modern image format that promises superior compression with little to no quality loss, making images on the web considerably faster. Comparing it to JPEG or PNG, WebP images are often 25-34% smaller in size, which means a significant improvement in speed and bandwidth savings.

Enabling WebP in Sitecore XP

1. Check Browser Support:

Before delving into WebP, it's essential to understand that not all browsers support this format. Most modern browsers do, but always check the current support status to ensure broad compatibility. "Can I Use" is a really cool platform where you can check the support of image formats: https://caniuse.com/webp.

2. Configuration:

Begin by adding WebP to the list of allowed media types in Sitecore:


<mediaType name="WebP" extensions="webp">
  <mimeType>image/webp</mimeType>
  ...
</mediaType>
    

3. Third party Integration:

In our case, we are using "Imazen.WebP", a third party tool to handle webp images. Just install the latest version via Nuget.

4. Configure MediaRequest Processor:

In order to deliver all images as webp now, we have to write our own Custom MediaRequest handler that transforms the images to the new format. Here is an example:


public class WebpProcessor
{
    public void Process(GetMediaStreamPipelineArgs args)
    {
        // Setting to disable the Webp delivering.
        if (!Settings.GetBoolSetting("Media.DeliverAsWebP.Enabled", false))
        {
            return;
        }

        Assert.ArgumentNotNull(args, "args");
            
        // The quality of the deliverd images is also editable via Setting. The default value is 80.
        int quality = Settings.GetIntSetting("Media.DeliverAsWebP.Quality", 80);

        var outputStream = args.OutputStream;

        // Check if stream is null or mimetype of current image is not allowed to convert to webp.
        if (outputStream == null || !IsValidMimeType(args.MediaData.MimeType))
        {
            return;
        }
            
        // Create bitmap out of input stream.
        Bitmap image = Image.FromStream(outputStream.Stream);

        try
        {
            var webpStream = CreateWebp(image, quality, outputStream.Stream);
            
            args.OutputStream = new MediaStream(webpStream, "webp", outputStream.MediaItem);
        }
        catch (Exception ex)
        {
            Log.Warn("Error while creating webp image", ex, this);
        }
    }
        
    // Creates the stream to a webp stream with the help of SimpleEncoder (Imazen.WebP).
    private Stream CreateWebp(Bitmap image, int quality, Stream stream)
    {
        SimpleEncoder encoder = new SimpleEncoder();
        encoder.Encode(image, stream, quality);
        return stream;
    }

    // With a setting we are checking if the image is valid (jpg or png in our case)
    // and can be converted to webp.
    private bool IsValidMimeType(string mimeType)
    {
        if (string.IsNullOrWhiteSpace(mimeType))
        {
            return false;
        }

        string[] mimeTypesToConvert = Settings.GetSetting("Media.DeliverAsWebP.ValidMimeTypes").Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

        return mimeTypesToConvert.Any(mime => mime.Equals(mimeType, StringComparison.InvariantCultureIgnoreCase));
    }
}

5. Patch MediaRequest Processor:

Now we have to patch the MediaRequest Processor and add the Settings:


<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <getMediaStream>
        <processor type="TheSitecoreChronicles.Project.MediaRequest.WebpProcessor, TheSitecoreChronicles.Project" patch:after="processor[@type='Sitecore.Resources.Media.RestoreColorProfileProcessor, Sitecore.Kernel']" />
      </getMediaStream>
    </pipelines>
    <settings>
      <setting name="Media.DeliverAsWebP.Enabled" value="true"/>
      <setting name="Media.DeliverAsWebP.ValidMimeTypes" value="image/jpeg|image/png"/>
      <setting name="Media.DeliverAsWebP.Quality" value="80"/>
    </settings>
  </sitecore>
</configuration>

6. Add LibWebP DLL:

To use the Imazen.Webp library we must download the "libwebp.dll" and insert it to our bin folder in the Website root. You can find the instructions here.

Conclusion

Implementing WebP images in your Sitecore XP website can significantly improve its performance, leading to a better user experience and potentially better search rankings. By following the steps outlined in this article, you can easily integrate WebP images into your Sitecore XP website and enjoy the benefits of this modern image format.

Happy coding! 😎

P.S.: For more informations about Sitecore and our Services, please visit www.cyber-solutions.at