Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Barry Arends 1 post 71 karma points
    May 22, 2024 @ 13:43
    Barry Arends
    0

    How do I set an Image (Imedia) FocalPoint programmatically

    Hi everyone,

    hopefully someone here knows how to solve this. I am trying to set the FocalPoint property (Image.UmbracoFile.FocalPoint) from code. The reason I am trying to do this is as I am importing content from a headless version of Umbraco (json) into a version of Umbraco that is going to server the content as a normal consumer website, where FocalPoints are already defined in the headless version. I am able to use the the IService API's in Umbraco 13 to upload and create the images (IMediaService) and its related content (IContentService) and the entire import is working fine, except where I am trying to copy the FocalPoint across.

    E.g. I've tried the below, but the problem with this code is that the IMedia object (ContentType = "Image") can not be casted into an Image type, nor am I sure how to get the Image instance of the IMedia object in this case...

                    var newMediaImage = (Umbraco.Cms.Web.Common.PublishedModels.Image)newMedia;
                    newMediaImage.UmbracoFile.FocalPoint = new Umbraco.Cms.Core.PropertyEditors.ValueConverters.ImageCropperValue.ImageCropperFocalPoint
                    {
                        Left = image.FocalPoint.Left,
                        Top = image.FocalPoint.Top
                    };
                    _mediaService.Save(newMedia);
    

    This is how the new Media object (Image) is being created:

        private IMedia CreateMediaImage(IMedia mediaProductFolder, string imageName, string imageFileName, string tempImagePath)
        {
            IMedia newMedia;
            using (Stream stream = System.IO.File.OpenRead(tempImagePath))
            {
                newMedia = _mediaService.CreateMedia(imageName, mediaProductFolder.Id, Constants.Conventions.MediaTypes.Image);
                newMedia.SetValue(_mediaFileManager, _mediaUrlGeneratorCollection, _shortStringHelper, _contentTypeBaseServiceProvider, Constants.Conventions.Media.File, imageFileName, stream);
                var newMediaResult = _mediaService.Save(newMedia);
            }
    
            return newMedia;
        }
    

    Any pointers on how to achieve this would be greatly appreciated.

    Thanks,

    Barry

Please Sign in or register to post replies

Write your reply to:

Draft