Copied to clipboard

Flag this post as spam?

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


  • Dmitry Morlender 19 posts 100 karma points
    Jan 09, 2018 @ 07:52
    Dmitry Morlender
    0

    Image Preprocessing on upload to media

    Hi everybody, I have the following code from: https://24days.in/umbraco-cms/2014/all-your-images-are-belong-to-umbraco/

    public class ApplicationEvents : ApplicationEventHandler
    {
        protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            // Tap into the Saving event
            MediaService.Saving += (sender, args) =>
            {
                MediaFileSystem mediaFileSystem = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>();
                IContentSection contentSection = UmbracoConfig.For.UmbracoSettings().Content;
                IEnumerable<string> supportedTypes = contentSection.ImageFileTypes.ToList();
    
                foreach (IMedia media in args.SavedEntities)
                {
                    if (media.HasProperty("umbracoFile"))
                    {
                        // Make sure it's an image.
                        string path = media.GetValue<string>("umbracoFile");
                        string extension = Path.GetExtension(path).Substring(1);
                        if (supportedTypes.InvariantContains(extension))
                        {
                            // Resize the image to 1920px wide, height is driven by the
                            // aspect ratio of the image.
                            string fullPath = mediaFileSystem.GetFullPath(path);
                            using (ImageFactory imageFactory = new ImageFactory(true))
                            {
                                ResizeLayer layer = new ResizeLayer(new Size(1920, 0), ResizeMode.Max)
                                {
                                    Upscale = false
                                };
    
                                imageFactory.Load(fullPath)
                                            .Resize(layer)
                                            .Save(fullPath);
                            }
                        }
                    }
                }
            };
        }
    }
    

    The code works perfectly on my local env. but doesn't work with Azure blob on stage env.

    Can you help me detecting what I'm doing wrong?

    Thank you in advance.

  • Alex Skrypnyk 6150 posts 24110 karma points MVP 8x admin c-trib
    Jan 10, 2018 @ 12:59
    Alex Skrypnyk
    0

    Hi Dmitry

    Welcome to our forum!

    You have to use UmbracoFileSystemProviders.Azure for working with images in Azure, have a look - https://our.umbraco.org/projects/collaboration/umbracofilesystemprovidersazure/

    /Alex

  • Dmitry Morlender 19 posts 100 karma points
    Jan 10, 2018 @ 13:01
    Dmitry Morlender
    0

    Hi Alex, I'm already using it. The images are uploaded as expected if I'm not trying to resize them, the thing is that I want to preprocess them before they get saved in order to reduce the image size.

  • Dmitry Morlender 19 posts 100 karma points
    Jan 18, 2018 @ 06:19
    Dmitry Morlender
    0

    Could someone give me a hint?

  • Tom Steer 161 posts 596 karma points
    Jan 18, 2018 @ 08:23
    Tom Steer
    102

    Hey Dmitry,

    Here is my modified version of that code which works with Azure Blob storage:

    public void PreProcessMediaItem(IMedia item, IMediaService mediaService, MediaFileSystem mediaFileService)
    {
        var contentSection = UmbracoConfig.For.UmbracoSettings().Content;
        var supportedTypes = contentSection.ImageFileTypes.ToList();
        if (!item.HasProperty(Constants.Conventions.Media.File))
            return;
        if (string.IsNullOrEmpty(item.GetValue<string>(Constants.Conventions.Media.File)))
            return;
    
        var umbracoFileProp = item.GetValue(Constants.Conventions.Media.File);
        string relativeImagePath;
    
        if (umbracoFileProp.ToString().DetectIsJson())
        {
            var cropObject = JsonConvert.DeserializeObject<ImageCropDataSet>(umbracoFileProp.ToString());
            relativeImagePath = cropObject.Src;
        }
        else
        {
            relativeImagePath = item.GetValue<string>(Constants.Conventions.Media.File);
        }
        // Make sure it's an image.
        var extension = Path.GetExtension(relativeImagePath).Substring(1);
        if (supportedTypes.InvariantContains(extension))
        {
            // Resize the image to _maxWidth wide, height is driven by the
            // aspect ratio of the image.
            using (var imageFactory = new ImageFactory(true))
            {
                var layer = new ResizeLayer(new Size(_maxWidth, 0), ResizeMode.Max)
                {
                    Upscale = false
                };
    
                using (var imageFileStream = mediaFileService.OpenFile(relativeImagePath))
                {
                    imageFactory.Load(imageFileStream).Resize(layer);
                }
    
                var resizedImage = imageFactory.Image;
    
                var newWidth = resizedImage.Width;
                var newHeight = resizedImage.Height;
                long bytes;
    
                using (var fileStream = new MemoryStream())
                {
                    imageFactory.Save(fileStream);
                    fileStream.Position = 0;
                    mediaFileService.AddFile(relativeImagePath, fileStream, true);
                    bytes = fileStream.Length;
                }
    
                // Set the correct meta values for the image.
                item.SetValue(Constants.Conventions.Media.Width, newWidth);
                item.SetValue(Constants.Conventions.Media.Height, newHeight);
                item.SetValue(Constants.Conventions.Media.Bytes, bytes);
            }
        }
    }
    

    Hope that helps.

    Tom

  • Dmitry Morlender 19 posts 100 karma points
    Jan 18, 2018 @ 08:57
    Dmitry Morlender
    1

    Thank you very much! looks like it works PERFECTLY on my test env.

  • Greg Woods 12 posts 92 karma points
    Oct 18, 2018 @ 05:23
    Greg Woods
    0

    Hi Tom

    Where do you call PreProcessMediaItem?

    Greg

  • Dmitry Morlender 19 posts 100 karma points
    Oct 18, 2018 @ 05:59
    Dmitry Morlender
    0

    It is getting called in the "ApplicationStarting" event when you subscribe to the media saving event.

  • Greg Woods 12 posts 92 karma points
    Oct 19, 2018 @ 01:57
    Greg Woods
    0

    Hi Dmitry

    Ah yeah I figured that out. I did change it slightly to not send in the mediaService and then removed the save.

    So ended up with this:

            protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            MediaService.Saving += (sender, args) =>
            {
                MediaFileSystem mediaFileSystem = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>();
    
                foreach (IMedia media in args.SavedEntities)
                {
                    if (media.HasProperty("umbracoFile"))
                    {
                        PreProcessMediaItem(media, mediaFileSystem);
                    }
                }
            };
        }
    

    And then removed this line in PreProcessMediaItem, as I'm already subscribing to the Save event:

                        //mediaService.Save(item, 0, false);
    
  • Matt Barlow | jacker.io 164 posts 740 karma points c-trib
    Nov 19, 2018 @ 17:30
    Matt Barlow | jacker.io
    0

    This is really great, but there is a slight issue with the width / height. I'm hooking into the MediaService saving event.

    protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        MediaService.Saving += (sender, args) =>
        {
            MediaFileSystem mediaFileSystem = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>();
            foreach (IMedia media in args.SavedEntities)
            {
                PreProcessMediaItem(media, sender, mediaFileSystem);
            }
        };
    }
    

    then have:

    public void PreProcessMediaItem(IMedia item, IMediaService mediaService, MediaFileSystem mediaFileService)
    {
        var contentSection = UmbracoConfig.For.UmbracoSettings().Content;
        var supportedTypes = contentSection.ImageFileTypes.ToList();
        if (!item.HasProperty(Constants.Conventions.Media.File))
            return;
        if (string.IsNullOrEmpty(item.GetValue<string>(Constants.Conventions.Media.File)))
            return;
    
        var umbracoFileProp = item.GetValue(Constants.Conventions.Media.File);
        string relativeImagePath;
    
        if (umbracoFileProp.ToString().DetectIsJson())
        {
            var cropObject = JsonConvert.DeserializeObject<ImageCropDataSet>(umbracoFileProp.ToString());
            relativeImagePath = cropObject.Src;
        }
        else
        {
            relativeImagePath = item.GetValue<string>(Constants.Conventions.Media.File);
        }
    
        var extension = Path.GetExtension(relativeImagePath).Substring(1);
        if (supportedTypes.InvariantContains(extension))
        {
            using (var imageFactory = new ImageFactory(true))
            {
                var layer = new ResizeLayer(new Size(1920, 0), ResizeMode.Max)
                {
                    Upscale = false
                };
                using (var imageFileStream = mediaFileService.OpenFile(relativeImagePath))
                {
                    imageFactory.Load(imageFileStream).Resize(layer);
                }
                var resizedImage = imageFactory.Image;
                var newWidth = resizedImage.Width;
                var newHeight = resizedImage.Height;
                long bytes;
                using (var fileStream = new MemoryStream())
                {
                    imageFactory.Save(fileStream);
                    fileStream.Position = 0;
                    mediaFileService.AddFile(relativeImagePath, fileStream, true);
                    bytes = fileStream.Length;
                }
                item.SetValue(Constants.Conventions.Media.Width, newWidth);
                item.SetValue(Constants.Conventions.Media.Height, newHeight);
                item.SetValue(Constants.Conventions.Media.Bytes, bytes);
            }
        }
    }
    

    Which is using the accepted answer (thanks Tom), but the width and height don't update on the media file properties. The image is resized and the file size updates, but the width and height don't.

    Any ideas?

    shown-details

    actual-details

Please Sign in or register to post replies

Write your reply to:

Draft