1

I have a need to auto compress images as they are uploaded to an image library. Using code or otherwise how could I go about this? I don't want to specify a fixed height / width but would rather maintain the aspect ratio and just downsize the image to be under x MB (if at all possible). Is something like this possible?

4

Useful link image compress that describes compressing images in image library.

Following code will automatically compress image while uploading.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Drawing;
using System.IO;

namespace PictureLibraryImageCrop
{
    public class PictureLibraryEventReciever : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            try
            {
                //Check user is site admin , remove it if you dont need it
                if (properties.OpenWeb().CurrentUser.IsSiteAdmin)
                {
                    SPFile file = properties.ListItem.File;
                    if (null != file)
                    {
                        properties.OpenWeb().AllowUnsafeUpdates = true;
                        try
                        {
                            MemoryStream msOut = new MemoryStream();
                            MemoryStream msIn = new MemoryStream(file.OpenBinary(), true);

                            int width = 100; //set to desired value 
                            int height = 200; //set to desired value 


                            Image img = Image.FromStream(msIn).GetThumbnailImage(width, height, null, IntPtr.Zero);

                            img.Save(msOut, System.Drawing.Imaging.ImageFormat.Jpeg);

                            file.SaveBinary(msOut, false);

                            file.CheckOut();

                            file.Update();

                            file.CheckIn(string.Empty);
                        }
                        finally
                        {
                            properties.OpenWeb().AllowUnsafeUpdates = false;
                        }
                    }
                }
            }
            catch
            {
                //Do some exception handling 
                throw;
            }

        }

    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.