Friday, March 15, 2013

Resizing an Image for consistency in SharePoint

While implementing intranet within our organization, we configure MySites within SharePoint, upload the user profiles from Active Directory and give users the ability to upload their own picture. Also, while implementing any News, or any company information, updates on the home page of Intranet, we tend to put pictures beside the text we write. Now, the image for several notifications can be of several size if you don’t have an in-house designer who trims/resizes your pictures to be uploaded to SharePoint. So, here comes my solution to resize images as we upload them to a definitive size which can then be uploaded and shown to users on the SharePoint.

I have created Synchronous event receiver to my Notification list where I am adding the image and the code resizes the image and uploads it to the list for a nice and consistent look and feel of your website.

Copy and paste the code below into your ItemAdded method.

       public override void ItemAdded(SPItemEventProperties properties)
       {
           int _imageWidth = 0;
           int _imageHeight = 0;

           if (properties.ListTitle.ToLower().Equals("intranet pictures"))
           {
               try
               {
                   string _width = properties.ListItem.File.Properties["vti_lastwidth"].ToString();
                   string _height = properties.ListItem.File.Properties["vti_lastheight"].ToString();

                   if (Int32.TryParse(_width, out _imageWidth) && Int32.TryParse(_height, out _imageHeight))
                   {
                       //checking if the image height and weight is 120 (for the sake of example)
                       if (_imageWidth != 120 || _imageHeight != 120)
                       {
                           SPFile _imageFile = properties.ListItem.File;

                           MemoryStream _inputStream = new MemoryStream(_imageFile.OpenBinary(), true);
                           MemoryStream _outputStream = new MemoryStream();

                           Image _resizedImage = Image.FromStream(_inputStream).GetThumbnailImage(120, Int32.Parse(_height), null, IntPtr.Zero);
                           _resizedImage.Save(_outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                           _imageFile.SaveBinary(_outputStream, false);                          

                       }
                   }
               }
               catch (Exception ex)
               {
                   properties.ListItem.Delete();
                   properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
                   //You can give the location of your custom error page here
                   properties.RedirectUrl = "/_layouts/Intranet_PictureRestrict/IntranetPicError.aspx";                   
               }
           }
       }
Let me know if you want to customize it more or have any queries.

No comments: