Responsive Images In ASP.NET: Converting Image Tag To Picture Tag
A picture tag allows us to serve different sized images based on different viewport breakpoints or pixel-ratios, resulting in better page load performance. Google's Pagespeed Insights negatively scores your site if responsive images aren't used. Pretty much all modern browsers support this markup and on the off chance it doesn't, an image fallback can be set.
Using the picture markup inside page templates is pretty straight-forward, but when it comes to CMS related content where HTML editors only accommodate image tags, it's really difficult to get someone like a client to add this form of markup. So the only workaround is to transform any image tag into a picture tag at code-level.
Code: ConvertImageToPictureTag Extension Method
The ConvertImageToPictureTag
method will perform the following tasks:
- Loop through all image tags.
- Get the URL of the image from the "src" attribute.
- Get other attributes such as "alt" and "style".
- Generate picture markup and add as many source elements based on the viewport breakpoints required, apply the URL of the image, style and alt text.
- Replace the original image tag with the new picture tag.
The ConvertImageToPictureTag
code uses HtmlAgilityPack, making it very easy to loop through all HTML nodes and manipulate the markup. In addition, this implementation relies on a lightweight client-side JavaScript plugin - lazysizes. The lazysizes plugin will delay the loading of the higher resolution image based on the viewport rules in the picture tag until the image is scrolled into view.
using HtmlAgilityPack;
using Site.Common.Kentico;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
namespace SurinderBhomra.Common.Extensions
{
public static class ContentManipulatorExtensions
{
/// <summary>
/// Transforms all image tags to a picture tag inside parsed HTML.
/// All source image URL's need to contain a "width" query parameter in order to have a resize starting point.
/// </summary>
/// <param name="content"></param>
/// <param name="percentageReduction"></param>
/// <param name="minimumWidth">The minimum width an image has to be to warrant resizing.</param>
/// <param name="viewPorts"></param>
/// <returns></returns>
public static string ConvertImageToPictureTag(this string content, int percentageReduction = 10, int minimumWidth = 200, params int[] viewPorts)
{
if (viewPorts?.Length == 0)
throw new Exception("Viewport parameter is required.");
if (!string.IsNullOrEmpty(content))
{
//Create a new document parser object.
HtmlDocument document = new HtmlDocument();
//Load the content.
document.LoadHtml(content);
//Get all image tags.
List<HtmlNode> imageNodes = document.DocumentNode.Descendants("img").ToList();
if (imageNodes.Any())
{
// Loop through all image tags.
foreach (HtmlNode imgNode in imageNodes)
{
// Make sure there is an image source and it is not externally linked.
if (imgNode.Attributes.Contains("src") && !imgNode.Attributes["src"].Value.StartsWith("http", StringComparison.Ordinal))
{
#region Image Attributes - src, class, alt, style
string imageSrc = imgNode.Attributes["src"].Value.Replace("~", string.Empty);
string imageClass = imgNode.Attributes.Contains("class") ? imgNode.Attributes["class"].Value : string.Empty;
string imageAlt = imgNode.Attributes.Contains("alt") ? imgNode.Attributes["alt"].Value : string.Empty;
string imageStyle = imgNode.Attributes.Contains("style") ? imgNode.Attributes["style"].Value : string.Empty;
#endregion
#region If Image Source has a width query parameter, this will be used as the starting size to reduce images
int imageWidth = 0;
UriBuilder imageSrcUri = new UriBuilder($"http://www.surinderbhomra.com{imageSrc}");
NameValueCollection imageSrcQueryParams = HttpUtility.ParseQueryString(imageSrcUri.Query);
if (imageSrcQueryParams?.Count > 0 && !string.IsNullOrEmpty(imageSrcQueryParams["width"]))
imageWidth = int.Parse(imageSrcQueryParams["width"]);
// If there is no width parameter, then we cannot resize this image.
// Might be an older non-responsive image link.
if (imageWidth == 0 || imageWidth <= minimumWidth)
continue;
// Clear the query string from image source.
imageSrc = imageSrc.ClearQueryStrings();
#endregion
// Create picture tag.
HtmlNode pictureNode = document.CreateElement("picture");
if (!string.IsNullOrEmpty(imageStyle))
pictureNode.Attributes.Add("style", imageStyle);
#region Add multiple source tags
StringBuilder sourceHtml = new StringBuilder();
int newImageWidth = imageWidth;
for (int vp = 0; vp < viewPorts.Length; vp++)
{
int viewPort = viewPorts[vp];
// We do not not want to apply the percentage reduction to the first viewport size.
// The first image should always be the original size.
if (vp != 0)
newImageWidth = newImageWidth - (newImageWidth * percentageReduction / 100);
sourceHtml.Append($"<source srcset=\"{imageSrc}?width={newImageWidth}\" data-srcset=\"{imageSrc}?width={newImageWidth}\" media=\"(min-width: {viewPort}px)\">");
}
// Add fallback image.
sourceHtml.Append($"<img src=\"{imageSrc}?width=50\" style=\"width: {imageWidth}px\" class=\"{imageClass} lazyload\" alt=\"{imageAlt}\" />");
pictureNode.InnerHtml = sourceHtml.ToString();
#endregion
// Replace the image node with the new picture node.
imgNode.ParentNode.ReplaceChild(pictureNode, imgNode);
}
}
return document.DocumentNode.OuterHtml;
}
}
return content;
}
}
}
To use this extension, add this to any string containing HTML markup, as so:
// The HTML markup will generate responsive images using based on the following parameters:
// - Images to be resized in 10% increments.
// - Images have to be more than 200px wide.
// - Viewport sizes to take into consideration: 1000, 768, 300.
string contentWithResponsiveImages = myHtmlContent.ConvertImageToPictureTag(10, 200, 1000, 768, 300);
Sidenote
The code I've shown doesn't carry out any image resizing, you will need to integrate that yourself. Generally, any good content management platform will have the capability to serve responsive images. In my case, I use Kentico and can resize images by adding a "width" and/or "height" query parameter to the image URL.
In addition, all image URL's used inside an image tags "src" attribute requires a width query string parameter. The value of the width parameter will be the size the image in its largest form. Depending on the type of platform used, the URL structure to render image sizes might be different. This will be the only place where the code will need to be retrofitted to adapt to your own use case.