Resize Image before uploading to SharePoint Image Library programmatically

n

nThere are some times when we might want to check /restrict the height and width of Image before uploading to SharePoint Images Library

n

nto address this situation , I have tried creating a event receiver which checks the width and height of image which we are uploading from file system , and If found big then resize to 200×200

n

npublic override void ItemAdded(SPItemEventProperties properties)

n

n{

n

n    int _imageWidth = 0;

n

n    int _imageHeight = 0;

n

n

n

n    if (properties.ListTitle.ToLower().Equals(“images”))

n

n    {

n

n      try

n

n      {

n

n        string _width = properties.ListItem.File.Properties[“vti_lastwidth”].ToString();

n

n        string _height = properties.ListItem.File.Properties[“vti_lastheight”].ToString();

n

n

n

n        if (Int32.TryParse(_width, out _imageWidth) && Int32.TryParse(_height, out _imageHeight))

n

n        {

n

n          if (_imageWidth > 200 && _imageHeight > 200)

n

n          {

n

n            SPFile _imageFile = properties.ListItem.File;

n

n

n

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

n

n            MemoryStream _outputStream = new MemoryStream();

n

n

n

n            Image _resizedImage = Image.FromStream(_inputStream).GetThumbnailImage(200, 200, null, IntPtr.Zero);

n

n            _resizedImage.Save(_outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

n

n

n

n             _imageFile.SaveBinary(_outputStream, false);

n

n             _imageFile.CheckOut();

n

n             _imageFile.Update();

n

n             _imageFile.CheckIn(“Image Resized”);

n

n             if (properties.ListItem.ParentList.EnableMinorVersions)

n

n             {

n

n               properties.ListItem.File.Publish(“ImagePublished”);

n

n             }

n

n             if (properties.ListItem.ParentList.EnableModeration)

n

n             {

n

n               properties.ListItem.File.Approve(“ImageApproved”);

n

n             }

n

n

n

n           }

n

n         }

n

n       }

n

n       catch (Exception ex)

n

n       {

n

n         throw new SPException(“Error: “ + ex.StackTrace);

n

n       }

n

n      }

n

n   }

n

n

n

nNote : use System.Drawing Namespace for using class Image
n
nReference : MSDN Forums Post

n

Leave a Comment