Tuesday, May 24, 2011

Resize Image before uploading to SharePoint Image Library programmatically

There are some times when we might want to check /restrict the height and width of Image before uploading to SharePoint Images Library
to 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 200x200
public override void ItemAdded(SPItemEventProperties properties)
{
    int _imageWidth = 0;
    int _imageHeight = 0;

    if (properties.ListTitle.ToLower().Equals("images"))
    {
      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))
        {
          if (_imageWidth > 200 && _imageHeight > 200)
          {
            SPFile _imageFile = properties.ListItem.File;

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

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

             _imageFile.SaveBinary(_outputStream, false);
             _imageFile.CheckOut();
             _imageFile.Update();
             _imageFile.CheckIn("Image Resized");
             if (properties.ListItem.ParentList.EnableMinorVersions)
             {
               properties.ListItem.File.Publish("ImagePublished");
             }
             if (properties.ListItem.ParentList.EnableModeration)
             {
               properties.ListItem.File.Approve("ImageApproved");
             }

           }
         }
       }
       catch (Exception ex)
       {
         throw new SPException("Error: " + ex.StackTrace);
       }
      }
   }

Note : use System.Drawing Namespace for using class Image

Reference : MSDN Forums Post

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Just what I'm looking for but... where do I add this code?
    Also, bit of a strech but if I wanted to reuse this on more than one area could it pull the 200x200 H & W from a user choice?

    ReplyDelete
  3. @Colin , this is a simple event receiver which overrides the ItemAdded event , you can put this code in the same event. here is small help on how to create SharePoint event receivers - http://msdn.microsoft.com/en-us/vstudio/ff623003.aspx
    about your second question - If you want to accept the height and width from the user before saving image to library, then better approach would be to create a web part and use the re-use the code to save image.

    ReplyDelete