Add ImageResizer to XhtmlString Optimizely CMS

Add ImageResizer to images in XhtmlString Optimizely CMS

icon of user profile

Published 4th october 2021
Optimizely CMS 11

This is a spin off episode of Tomas Henserud Gullas blog post about adding lazyload to images

By using the same approach you may add ImageResizer to images used by editors in the Wysiwyg, and this is a pretty good idea since you never know what editors might be up to when they get free hands. They could upload too large images, and in wrong formats.

Add the following extension

public static class XhtmlStringExtensions
   public static XhtmlString AddImagesResizer(this XhtmlString xhtmlString, int width=700, int quality=70)
      if (PageEditing.PageIsInEditMode)
         return xhtmlString;

      var processedText = Regex.Replace(xhtmlString.ToInternalString(), "(.aspx)", $"$1?w={width}&mode=crop&quality=70&format=webp");

      return new XhtmlString(processedText);

Added some optional parameters also, width and quality. In my case, the width of text never is larger then 700px, therefor i use 700, may be other in your implementation.

The regex is quite simple (.aspx) … thats because the internal string, displays internal images as .aspx links, like this:

<img class="img-responsive" src="~/link/f3d5fb06a26744459ae213f2218560a8.aspx" alt="" />

After regex code run:

<img class="img-responsive" src="~/link/f3d5fb06a26744459ae213f2218560a8.aspx?w=700&mode=crop&quality=70&format=webp" alt="" />

Then in /Views/Shared/DisplayTemplates/ add this in XhtmlString.cshtml:

@using EPiServer.Core

@model XhtmlString

    if (Model == null) { return; };


Or to be used with Tomas Lazyload:


Or can be use in the cshtml view directly with parameters:

@{Html.RenderXhtmlString(Model.CurentPage.MainBody.AddImageResizer(width: 400, quality: 40));}

About the author

Luc Gosso
– Independent Senior Web Developer
working with Azure and Episerver

Twitter: @LucGosso