Resizing an Image while adding as an attachment to a list Item

Event handler code to resize an an image when added as an attachment to a list item.

public override void ItemAdded(SPItemEventProperties properties)
     if (String.Compare(properties.ListTitle, “Brief Participant Details”, true) == 0)
         SPSite siteColl = new SPSite(properties.SiteId);
         SPWeb site = siteColl.OpenWeb(properties.RelativeWebUrl);
         SPList listCFPrint = site.Lists[properties.ListTitle];
         ResizeImage resize = new ResizeImage();
         if (properties.ListItem.Attachments.Count > 0)
              string fileName = properties.ListItem.Attachments[0].ToString();
              string strPath = properties.ListItem.Attachments.UrlPrefix + fileName;
              SPWeb web = new SPSite(properties.WebUrl).OpenWeb();
              //Get the item
             SPListItem item = properties.ListItem;

             //Get the folder
             SPFolder folder = web.Folders[“Lists”].SubFolders[properties.ListTitle].SubFolders[“Attachments”].SubFolders[item.ID.ToString()];
             SPFile file = folder.Files[0];
             byte[] binFile = file.OpenBinary();
             System.IO.FileStream fstream = System.IO.File.Create(“c:\\UploadedPhotos\\” + file.Name);
             fstream.Write(binFile, 0, binFile.Length);

             //Resize the Image
             byte[] imgResized = resize.Resize(“C:\\UploadedPhotos\\” + fileName);

            //Delete the imag from the attachments
             //Add the resized imaged to the attachments
             properties.ListItem.Attachments.Add(fileName, imgResized);
             File.Delete(“C:\\UploadedPhotos\\” + fileName);


using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace PhotoResizeEventHandler
     class ResizeImage
          public byte[] Resize(string ORIG_PHOTO_URL)
                //Read the original photo in as a byte array
                byte[] rawData = File.ReadAllBytes(ORIG_PHOTO_URL);

               //Crop our file, pass in the new dimensions
               byte[] newImage = ResizeImageFile(rawData, 150);
               return newImage;

          private static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
               Image original = Image.FromStream(new MemoryStream(imageFile));
               int targetH, targetW;
               if (original.Height > original.Width)
                   targetH = targetSize;
                   targetW = (int)(original.Width * ((float)targetSize / (float)original.Height));
                   targetW = targetSize;
                   targetH = (int)(original.Height * ((float)targetSize / (float)original.Width));
              Image imgPhoto = Image.FromStream(new MemoryStream(imageFile));
              // Create a new blank canvas. The resized image will be drawn on this canvas.
              Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
              bmPhoto.SetResolution(72, 72);
              Graphics grPhoto = Graphics.FromImage(bmPhoto);
              grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
              grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
              grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
              grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);

              // Save out to memory and then to a file. We dispose of all objects to make sure the files don’t stay locked.
              MemoryStream mm = new MemoryStream();
              bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
              return mm.GetBuffer();



2 thoughts on “Resizing an Image while adding as an attachment to a list Item

Add yours

  1. Hi,i am newbie for shrepoint.
    our aim is to save end user career details and resume in to the list.
    we saved the career details. but we cannot able to attach the reusme to the custom list attachment.
    we generated entity class for custom list.
    we have manager class and business validation class.
    from user control we pass the EntityClass Item and its value to validation class.
    from there it calls busniess layer to save the details in to column.
    where as for resume we cannot attach the documents to list attachment.
    please help me.
    from the entity class i don’t see any column value for attachment.
    from user control on click event for save.
    public bool SaveApplications()
    FertilApplicantsValidation = new FertilApplicantsValidation();
    FertilVacancyApplicationsItem item = new FertilVacancyApplicationsItem();
    item.ApplicantName = txtName.Text.ToString().Trim();
    item.ApplicantEmail = txtEmail.Text.ToString().Trim();
    item.ApplicantContactNumber = txtContact.Text.ToString().Trim();
    item.ApplicationDate = DateTime.Now;
    FertilApplicantsValidation = new FertilApplicantsValidation();
    return FertilApplicantsValidation.SaveFertilApplicnats(URL, item);

    from Validation class
    public bool SaveFertilApplicnats(string webUrl, FertilVacancyApplicationsItem item)
    bool isSave = false;
    try {
    using (FertilVacancyManager manager = new FertilVacancyManager(webUrl))
    isSave = manager.saveFertilApplicantsData(item);
    catch (Exception ex)
    Logger.Instance.Error(“FertilVacancyValidation_getFertilApplicantsData”, ex);
    return isSave;
    From manager class
    public bool saveFertilApplicantsData(FertilVacancyApplicationsItem item) {
    try {
    using (ContextSwitch cSwitch = new ContextSwitch()) {
    m_ApplicantsdataContext = cSwitch.GetFertilApplicantsDataContext(m_webUrl); m_ApplicantsdataContext.FertilVacancyApplications.InsertOnSubmit(item); m_ApplicantsdataContext.SubmitChanges();
    } catch (Exception ex) { Logger.Instance.Error(“VacancyManager_getFertilApplicantsData”, ex);
    return false; }
    return true; }

  2. This has helped our organization solve an issue we were having (unrelated to image resizing).

    Thank you very much for taking the time to post this! Your efforts are greatly appreciated.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a website or blog at

Up ↑

%d bloggers like this: