Optimize images added in the rich text editor.

PictureRenderer for Optimizely CMS can be used to optimize images added in the rich text editor (TinyMce). In PictureRenderer.Optimizely v2.3 an XhtmlString extension is added that replaces img elements in the rich text content with a picture element.

You enable this by creating a display template for XhtmlString properties. Create the file /Views/Shared/DisplayTemplates/XhtmlString.cshtml and add this:

@using PictureRenderer.Optimizely
@model XhtmlString

@{ if (Model == null) { return; }; }
@{Html.RenderXhtmlString(Model.RenderImageAsPicture());}

If you want a more fine grained control of which Xhtml properties that should renderer picture elements, you can do this in your cshtml view:

@{ Html.RenderXhtmlString(Model.CurrentPage.MainBody.RenderImageAsPicture()); }

Now the editor can add an image of any size and it will be resized, converted to a more optimal format, and lazy loaded!

RenderImageAsPicture takes a picture profile as input parameter, this lets you adapt how the picture element is rendered. It’s possible to change maximum image width (default value: 1024), image quality (default value: 80), and what image types that should be converted to WebP (default: jpg).
Example of how to set the quality value to 85:

@{ Html.RenderXhtmlString(Model.CurrentPage.MainBody.RenderImageAsPicture(new RichTextPictureProfile() {Quality = 85})); }


Thanks to Luc Gosso and Tomas Hensrud Gulla for inspiration on how to make this happen.

Leave a Reply