Home
Search

Start | Blogs | Umbraco | Map crop url

2019-10-23

Umbraco

How to map GetCropUrl in Umbraco

Update 2020-09-13:

For Umbraco 8.6.4 and above the last line in MapFromImageCropperAttribute looks like this:

property.SetValue(model, imageCropperValue.Src + imageCropperValue.GetCropUrl(CropName, Current.ImageUrlGenerator, useFocalPoint: true));

On my Blog post pages I have a Image Cropper property editor for a property called TeaserMedia, which is used for the images on the start page. On the editor I have defined a media crop alias "startPage" which is 500x500. In my code I retrieve all of the blog posts as IPublishedContent and map them to a view model. The problem was that I had to foreach every item and run .GetCropUrl() for every blog post as IPublishedContent in order to retrieve the crop urls. I did not want to loop and simply use UmbracoMapper.MapCollection and be done with it. I checked the documentation on Andy Butland's readme on GitHub but could not find anything. So I simply created a issue and asked Andy if it was possible, and not even an hour later I got an answer!

So what you need to do is create an attribute that implements IMapFromAttribute:

using System;
using System.Reflection;
using Umbraco.Core.PropertyEditors.ValueConverters;
using Zone.UmbracoMapper.V8;
using Zone.UmbracoMapper.V8.Attributes;

namespace Rasolo.Core.Features.Shared.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class MapFromImageCropperAttribute : Attribute, IMapFromAttribute
{
public string CropName { get; set; }

public void SetPropertyValue<T>(object fromObject, PropertyInfo property, T model, IUmbracoMapper mapper)
{
var imageCropperValue = fromObject as ImageCropperValue;
if (imageCropperValue == null)
{
return;
}

property.SetValue(model, imageCropperValue.Src + imageCropperValue.GetCropUrl(CropName));
}
}
}

and then I have created a property called TeaserMediaUrl for the url of the cropped image on the page.
On the property I have two attributes:

  1. Property mapping
  2. MapFromImageCropper

Property mapping to tell it to map to the source property which is the TeaserMedia property of ImageCropper.
MapFromImageCropper which is the newly created Attribute telling it which crop it is I want to map to. The property looks like this:


[PropertyMapping(SourceProperty = BlogPostPagePropertyAlias.TeaserMedia)]
[MapFromImageCropper(CropName = BlogPostPageMediaCropAliases.StartPage)]
public string TeaserMediaUrl { get; set; }

Where "BlogPostPagePropertyAlias.TeaserMedia" is simply a constant string with the value "teaserMedia" and "BlogPostPageMediaCropAlias.StartPage" is also a constant string of "startPage" which is the crop alias.

Now this property will automatically be mapped with the url to the cropped image. Now I can use UmbracoMapper.MapCollection and be done with it!

All credit goes to Andy Butland and 21robin12 on GitHub!