bradleykronson
3/29/2017 - 3:10 PM

Media service event that prebuilds for imageprocessor.web (from http://24days.in/umbraco-cms/2014/all-your-images-are-belong-to-umbraco/)

Media service event that prebuilds for imageprocessor.web

(from http://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);
                        }
                    }
                }
            }
        };
    }
}