using Microsoft.AspNetCore.Mvc;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.PropertyEditors.ValueConverters;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
namespace Umbraco.Docs.Samples.Web.Property_Editors_Add_Values;
[ApiController]
[Route("/umbraco/api/createimagecroppervalues")]
public class CreateImageCropperValuesController : Controller
{
private readonly IContentService _contentService;
private readonly IMediaService _mediaService;
private readonly MediaUrlGeneratorCollection _mediaUrlGeneratorCollection;
private readonly IJsonSerializer serializer;
public CreateImageCropperValuesController(
IContentService contentService,
IMediaService mediaService,
MediaUrlGeneratorCollection mediaUrlGeneratorCollection, IJsonSerializer serializer)
{
_contentService = contentService;
_mediaService = mediaService;
_mediaUrlGeneratorCollection = mediaUrlGeneratorCollection;
this.serializer = serializer;
}
// /Umbraco/Api/CreateImageCropperValues/CreateImageCropperValues
[HttpPost("createimagecroppervalues")]
public ActionResult<bool> CreateImageCropperValues()
{
// Create a variable for the GUID of the page you want to update
var contentKey = Guid.Parse("89974f8b-e213-4c32-9f7a-40522d87aa2f");
// Get the page using the GUID you've defined
IContent? content = _contentService.GetById(contentKey);
if (content == null)
{
return false;
}
// Create a variable for the GUID of the media item you want to use
var mediaKey = Guid.Parse("b6d4e98a-07c0-45f9-bfcc-52994f2806b6");
// Get the desired media file
IMedia? media = _mediaService.GetById(mediaKey);
if (media == null)
{
return false;
}
// Create a variable for the image cropper and set the source
var imageCropperValue = new ImageCropperValue
{
Src = media.GetUrl("umbracoFile", _mediaUrlGeneratorCollection)
};
// Serialize the image cropper value
var propertyValue = serializer.Serialize(imageCropperValue);
// Set the value of the property with alias "cropper"
// - remember to add the "culture" parameter if "cropper" is set to vary by culture
content.SetValue("cropper", propertyValue);
return _contentService.Save(content).Success;
}
}