Umbraco image crop helper

I'm a big fan of the image cropper data type in Umbraco. I mostly use it to generate three image variants of varying aspect ratios for desktop, tablet and mobile. I want to share some code that I find particularly useful when rendering the image crops on my templates.

The first is the code for an MVC html helper. This code outputs three data attributes (desktop, tablet and mobile) whose values are the paths to the images for the associated crop. The code accepts an Image object, which is a complex model that I create to hold image data.

public static class ImageCropperHelper
{
	public static MvcHtmlString ImageCropPaths(this HtmlHelper htmlHelper, Image image)
	{
		String result = String.Empty;

		try
		{
			String randParam = DateTime.Now.ToString("yyyyMMddHH") + (Math.Ceiling(((Decimal)DateTime.Now.Minute / 5)) * 5).ToString("00");

			if (image != null)
			{
				for (Int32 i = 0; i < image.CurrentImageData.Crops.Count; i++)
				{
					result += String.Format(" data-imagecrop-{0}=\"{1}?crop={2},{3},{4},{5}&cropmode=percentage&width={6}&height={7}&rnd={8}\"",
						image.CurrentImageData.Crops[i].Alias,
						image.CurrentImageData.Src,
						image.CurrentImageData.Crops[i].Coordinates.x1,
						image.CurrentImageData.Crops[i].Coordinates.y1,
						image.CurrentImageData.Crops[i].Coordinates.x2,
						image.CurrentImageData.Crops[i].Coordinates.y2,
						image.CurrentImageData.Crops[i].Width,
						image.CurrentImageData.Crops[i].Height,
						randParam);
				}
			}
		}
		catch { }

		return MvcHtmlString.Create(result);
	}
}

If you are creating a multi-lingual website, be advised that commas might be inserted into the helper output string in place of decimal points. This can be addressed easily with a simple replace on the coordinate data. As you can see from the usage below, the src attribute of the image tag is empty:

@using ChrisLovesDotNet.WebUI.HtmlHelpers

This is where the next code snippet comes in to play. The javascript function sets the img tag src attribute to the appropriate data-imagecrop attribute based on the screen width.

function responsiveImageLoading() {
    var windowWidth = $(window).width();
    var dataAttributeName = windowWidth <= 475 ? 'data-imagecrop-mobile' :
        (windowWidth > 475 && windowWidth <= 991 ? 'data-imagecrop-tablet' :
        'data-imagecrop-desktop');

    $('div[' + dataAttributeName + ']').each(function () {
        var src = $(this).attr(dataAttributeName)
        $(this).css('background-image', 'url("' + src + '")');
    });

    $('img[' + dataAttributeName + ']').each(function () {
        var src = $(this).attr(dataAttributeName)
        $(this).attr('src', src);
    });
}