If you want control over the markup using C# then you can try something like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<renderField>
<processor
patch:instead="processor[@type='Sitecore.Pipelines.RenderField.GetImageFieldValue, Sitecore.Kernel']"
type="Company.Foundation.Media.Pipelines.RenderField.GetImageFieldValue, Scms.Foundation.Media" />
</renderField>
</pipelines>
</sitecore>
</configuration>
using Sitecore.Diagnostics;
using Sitecore.Pipelines.RenderField;
namespace Company.Foundation.Media.Pipelines.RenderField
{
public class GetImageFieldValue : Sitecore.Pipelines.RenderField.GetImageFieldValue
{
public override void Process(RenderFieldArgs args)
{
Assert.ArgumentNotNull((object)args, nameof(args));
if (!this.IsImage(args))
{
return;
}
var renderer = new ImageRendererEx();
this.ConfigureRenderer(args, renderer);
this.SetRenderFieldResult(renderer.Render(), args);
}
}
}
using System.IO;
using System.Text;
using System.Xml.Linq;
using Sitecore;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Xml.Xsl;
namespace Company.Foundation.Media.Pipelines.RenderField
{
public class ImageRendererEx : ImageRenderer
{
public override RenderFieldResult Render()
{
var obj = Item;
if (obj == null)
{
return RenderFieldResult.Empty;
}
var attributes = Parameters;
if (attributes == null)
{
return RenderFieldResult.Empty;
}
var width = MainUtil.GetInt(Extract(attributes, "width", "w"), 0);
var height = MainUtil.GetInt(Extract(attributes, "height", "h"), 0);
var scale = MainUtil.GetFloat(Extract(attributes, "scale", "sc"), 0.0f);
var maxWidth = MainUtil.GetInt(Extract(attributes, "maxWidth", "mw"), 0);
var maxHeight = MainUtil.GetInt(Extract(attributes, "maxHeight", "mh"), 0);
var innerField = obj.Fields[FieldName];
if (innerField == null) return base.Render();
var imageField = new ImageField(innerField, FieldValue);
ParseField(imageField);
AdjustImageSize(imageField, scale, maxWidth, maxHeight, ref width, ref height);
if (imageField.MediaItem == null) return base.Render();
var imageMediaItem = new MediaItem(imageField.MediaItem);
if (imageMediaItem.MimeType == "image/svg+xml")
{
return new RenderFieldResult(RenderSvgImage(imageMediaItem, width, height));
}
return base.Render();
}
private string RenderSvgImage(MediaItem mediaItem, int width, int height)
{
Assert.ArgumentNotNull(mediaItem, nameof(mediaItem));
string result;
using (var reader = new StreamReader(mediaItem.GetMediaStream(), Encoding.UTF8))
{
result = reader.ReadToEnd();
}
var svg = XDocument.Parse(result);
if (svg.Document?.Root == null) return result;
if (width > 0)
{
svg.Document.Root.SetAttributeValue("width", width);
}
if (height > 0)
{
svg.Document.Root.SetAttributeValue("height", height);
}
result = svg.ToString();
return result;
}
}
}
Comments: If you really want to be fancy you can use similar code but turn it into a Scriban function.