Instantly share code, notes, and snippets.

Embed
What would you like to do?
using MyEpiSite.Business.Rendering;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
namespace MyEpiSite.Helpers
{
public static class PictureHelper
{
public static IHtmlString Picture(this HtmlHelper helper, string imageUrl, ImageType imageType, string cssClass = "")
{
//create picture element
var pictureElement = new TagBuilder("picture");
if (imageType.SrcSetWidths != null)
{
//add source element to picture element
var sourceElement = GetSourceElement(imageUrl, imageType);
pictureElement.InnerHtml += sourceElement.ToString(TagRenderMode.SelfClosing);
}
//create img element
var imgElement = new TagBuilder("img");
imgElement.Attributes.Add("src", imageUrl + GetQueryString(imageType.DefaultImgWidth));
if (!string.IsNullOrEmpty(cssClass))
{
imgElement.Attributes.Add("class", cssClass);
}
//add img element to picture element
pictureElement.InnerHtml += imgElement.ToString(TagRenderMode.SelfClosing);
return new MvcHtmlString(pictureElement.ToString());
}
private static TagBuilder GetSourceElement(string imageUrl, ImageType imageType)
{
var sourceElement = new TagBuilder("source");
//add srcset attribute
var srcset = string.Empty;
foreach (var width in imageType.SrcSetWidths)
{
srcset += imageUrl + GetQueryString(width) + " " + width + "w, ";
}
sourceElement.Attributes.Add("srcset", srcset);
//add sizes attribute
var sizes = string.Empty;
foreach (var size in imageType.SrcSetSizes)
{
sizes += size + ", ";
}
sourceElement.Attributes.Add("sizes", sizes);
return sourceElement;
}
private static string GetQueryString(int? imageWidth)
{
var qs = "?width=" + imageWidth;
//check appsetting if debug-info should be printed on image
bool.TryParse(ConfigurationManager.AppSettings["ImageProcessorDebug"], out var showDebugInfo);
if (showDebugInfo)
{
qs += $"&watermark=width:%20{imageWidth}&color=FF2D31&fontsize=40&textposition={imageWidth / 2 - 80},100";
}
return qs;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment