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

Posted: November 17, 2009 in Code, EventHandlers

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);
             fstream.Close();

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

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

\\\\ResizeImage.cs\\\\

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));
              }
              else
              {
                   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);
              original.Dispose();
              imgPhoto.Dispose();
              bmPhoto.Dispose();
              grPhoto.Dispose();
              return mm.GetBuffer();
          }
     }

}


Advertisements
Comments
  1. sathishkumar says:

    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. sathishkumar@fohmics.com
    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;
    item.VaccantidId.Add(int.Parse(VaccantID));
    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. Great Article!! says:

    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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s