Get focal point of media item (as opposed to local crop focal point)

I’d like to get the focal point coordinates of a media item in Umbraco 13 to use as CSS object-position values. I can get the focal point of local crops like this:

var focalX = 0.5M;
var focalY = 0.5M;
var focalPoint = myContent.Image?.LocalCrops?.FocalPoint;

if (focalPoint != null)
{
    focalX = focalPoint.Left;
    focalY = focalPoint.Top;
}

However, I’d prefer to use the focal point which is set on the media item itself rather than the local crop focal point. Is this possible? If so, how?

1 Like

Yep! I’ve done exactly this before. You need to get the umbracoFile property out of the Image as IPublishedContent.

var focalX = 0.5M;
var focalY = 0.5M;
var crops = myContent.Image?.Value<ImageCropperValue>("umbracoFile");

if (crops != null)
{
    focalX = crops.FocalPoint.Left;
    focalY = crops.FocalPoint.Top;
}

If you’re using ModelsBuilder and have an Image model from the out-of-the-box types, you could do it like this:

var focalX = 0.5M;
var focalY = 0.5M;
var img = myContent.Image.Content as Image;
var crops = img.UmbracoFile.Crops;

if (crops != null)
{
    focalX = crops.FocalPoint.Left;
    focalY = crops.FocalPoint.Top;
}

Thanks Rick. This seems to do the trick:

var focalX = 0.5M;
var focalY = 0.5M;
var img = myContent.Image?.Content as Image;
var focalPoint = img.UmbracoFile.FocalPoint;

if (focalPoint != null)
{
    focalX = Math.Round(focalPoint.Left * 100, 1);
    focalY = Math.Round(focalPoint.Top * 100, 1);
}
1 Like