Search code examples
c#asp.net-mvcimageumbracoumbraco7

How to get image width with Umbraco Media Service Saving Event


I am looking for a way to get the width of an image with an Umbraco event, to validate that the image respects a certain aspect ratio before being uploaded. The thing is I don't know if casting the mediaItem to Image is even possible. How can I get the width or the height here is my event code so far:

public class ImageResizer : ApplicationEventHandler
{
    protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        MediaService.Saving += MediaServiceSaving;
    }
    void MediaServiceSaving(IMediaService sender, SaveEventArgs<IMedia> e)
    {
        foreach (var mediaItem in e.SavedEntities)
        {
            Image img = (Image)mediaItem;
            double height = img.Height;
            double width = img.Width;
            string msg = "" + height;
            if (height / width != 1)
            {
                msg = "Ratio is not 1:1. Please make sure the width and height of your image is the same.";
                BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.success, "Error", msg);
            }
            else
            {
                //Ducplicate image to images and thubnails of desired choice
                //Send images to database - continue normal process
            }
        }
    }
}

Solution

  • Just trust Umbraco and let it do the hard work of figuring out if it's an image or not:

    public class ImageResizer : ApplicationEventHandler
    {
            protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
            {
                MediaService.Saving += MediaServiceSaving;
            }
            void MediaServiceSaving(IMediaService sender, SaveEventArgs<IMedia> e)
            {
                foreach (var mediaItem in e.SavedEntities)
                {
                    //if it's an image, the content type will tell you.
                    if(mediaItem.ContentType.Alias == "Image")
                    {
                        var width = Convert.ToDouble(mediaItem.Properties["umbracoWidth"].Value);
                        var height = Convert.ToDouble(mediaItem.Properties["umbracoHeight"].Value);
    
                        if (height / width != 1)
                        {                        
                      //Sending a message will cancel the process, so you don't
                      //need an else (unless you want to do something else with the image of course.
                            e.Messages.Add(new EventMessage("Wrong Ratio", "Ratio is not 1:1. Please make sure the width and height of your image is the same.", EventMessageType.Error));                        
                        }                    
                    }
                }
            }
    }