Tuesday 21 May 2013

Restricting picture size in ItemAdding event receiver for SharePoint picture library


If you want to restrict user from uploading a picture larger then specified size (width x height) then you can use code below.

Please note it only works when user uploads a single picture file, when user uploads multiple files, SharePoint opens Microsoft picture manager to upload several pictures hence HTTP Context comes as null. I tried to find a fix for it but I couldn't so if someone reading this post please comment the solution. Until then you can disable multiple picture uploads to library.

Ways around would be create a custom list definition and then a custom upload form with all of code logic behind, you can make it work for single files or several files but depends on your code behind logic and requirements.



class PicLibraryImageSize : SPItemEventReceiver
    {
        HttpContext _current;
        public PicLibraryImageSize()
        {
            _current = HttpContext.Current;
        }

        public override void ItemAdding(SPItemEventProperties properties)
        {
            try
            {
                this.DisableEventFiring();

                if (IspicTooLarge())
                {
                    properties.Cancel = true;
                    properties.ErrorMessage = "Picture Too large to upload !";
                }
            }
            catch (Exception ex)
            {
                //Log it
            }
            finally
            {
                this.EnableEventFiring();
            }
        }

        private bool IspicTooLarge()
        {
            HttpFileCollection cFiles = _current.Request.Files;

            HttpPostedFile pFile = cFiles[0];

            using (System.Drawing.Image image = System.Drawing.Image.FromStream(pFile.InputStream))
            {
                if (image.Width > 800 ||  image.Height > 600)
                {
                    return true;
                }
                else
                    return false;
            }
        }
    }

1 comment:

  1. I tried using the above code in the itemadding eventreceiver but still getting _current is null

    ReplyDelete