Skip to content

Instantly share code, notes, and snippets.

@kamsar
Created July 23, 2014 06:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamsar/65f167c0a256bd4b90ba to your computer and use it in GitHub Desktop.
Save kamsar/65f167c0a256bd4b90ba to your computer and use it in GitHub Desktop.
Sitecore 7,2-compatible rich text image dimension stripper
// Strips width and height attributes from Sitecore field rendered images without messing with the
// resizer's width and height attributes (as opposed to maxwidth/maxheight)
public class DimensionStrippingGetImageFieldValue : GetImageFieldValue
{
protected override Sitecore.Xml.Xsl.ImageRenderer CreateRenderer()
{
return new ImageRenderer();
}
private class ImageRenderer : Sitecore.Xml.Xsl.ImageRenderer
{
public override RenderFieldResult Render()
{
var baseResult = base.Render();
if (baseResult.IsEmpty) return baseResult;
var imageHtml = baseResult.FirstPart;
imageHtml = imageHtml.ReplaceRegex("(width|height)=\"([^']*?)\" ", string.Empty);
return new RenderFieldResult(imageHtml);
}
}
}
// Sitecore 7.2's rich text editor uses inline style attributes to set image width/height. This strips those style attributes.
public class StripRichTextImageFixedDimensions
{
public void Process(RenderFieldArgs args)
{
if (args.FieldTypeKey == "rich text")
{
Profiler.StartOperation("Stripping image tag dimensions from field: " + args.FieldName);
args.Result.FirstPart = StripDimensions(args.Result.FirstPart);
Profiler.EndOperation();
}
}
private static string StripDimensions(string text)
{
if (string.IsNullOrWhiteSpace(text))
{
return text;
}
string outText = text;
try
{
var doc = new HtmlDocument();
doc.LoadHtml(outText);
StripImageStyleAttributes(doc, "width", "height");
outText = doc.DocumentNode.WriteContentTo();
}
catch (Exception ex) { Log.Error("Error removing dimensions from HTML!", ex); }
return outText;
}
private static void StripImageStyleAttributes(HtmlDocument doc, params string[] styleAttributes)
{
// For reasons surpassing all understanding, HtmeAgilityPack returns null instead of an empty collection
// when the query finds no results.
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//img[@style]");
if (nodes == null || nodes.Count.Equals(0))
{
return;
}
foreach (HtmlNode node in nodes)
{
// find each style declaration and remove any attributes that match our kill-list
var validStyles = node.GetAttributeValue("style", string.Empty).Split(';')
.Select(x => x.Trim())
.Where(x=>!styleAttributes.Contains(x.Split(':').First().Trim()));
node.SetAttributeValue("style", string.Join(";", validStyles));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment