Upload User Profile Pictures Programmatically – SharePoint 2013


We are going to migration SharePoint 2007 User profile data to SharePoint 2013. Since we disabled the MySite in SP2007 and created our own custom list to stored user photos, there are only one profile picture per user.

This code will generate three thumbnails using sealed function in Microsoft.Office.Server.UserProfiles.UserProfilePhotos and update the PictureUrl property accordingly.

private void UploadProfileImages(string path, string url)
  using (SPSite site = new SPSite(url))
    SPServiceContext serverContext = SPServiceContext.GetContext(site);
    UserProfileManager userProfileManager = new UserProfileManager(serverContext);

    using (SPWeb web = site.OpenWeb())
      SPFolder subfolderForPictures = web.Folders["User Photos"].SubFolders["Profile Pictures"];
      // Get all image files in a folder
      DirectoryInfo dir = new DirectoryInfo(path);
      FileInfo[] Images = dir.GetFiles();
      foreach (FileInfo img in Images)
        string imageFilePath = path + "\\" + img.Name;
        string accountName = img.Name;

        // if User Profile exists then upload the images
        if (userProfileManager.UserExists(accountName))
          UploadPhoto(accountName, imageFilePath, subfolderForPictures);
          SetPictureUrl(accountName, subfolderForPictures, userProfileManager.GetUserProfile(accountName));
        {    Console.WriteLine("User {0} does not exist.", accountName);  }
      } // end of loop
} // end of function

private void UploadPhoto(string accountName, string imageFilePath, SPFolder subfolderForPictures)
  if (!File.Exists(imageFilePath) || Path.GetExtension(imageFilePath).Equals(".gif"))
  {  Console.WriteLine("File '{0}' does not exist or has invalid extension", imageFilePath);  }
    FileStream file = File.Open(imageFilePath, FileMode.Open);
    BinaryReader reader = new BinaryReader(file);

    if (subfolderForPictures != null)
      // try casting length (long) to int
      byte[] buffer = reader.ReadBytes((int)file.Length);

      int largeThumbnailSize = 300; 
      int mediumThumbnailSize = 72; 
      int smallThumbnailSize = 48; 

      using (MemoryStream stream = new MemoryStream(buffer))
        using (Bitmap bitmap = new Bitmap(stream, true))
          CreateThumbnail(bitmap, largeThumbnailSize, largeThumbnailSize, subfolderForPictures, accountName + "_LThumb.jpg");
          CreateThumbnail(bitmap, mediumThumbnailSize, mediumThumbnailSize, subfolderForPictures, accountName + "_MThumb.jpg");
          CreateThumbnail(bitmap, smallThumbnailSize, smallThumbnailSize, subfolderForPictures, accountName + "_SThumb.jpg");
    Console.WriteLine("Uploading image '{0}' for user '{1}'", imageFilePath, accountName);
} // end of function

/// Get sealed function to generate new thumbernails
public SPFile CreateThumbnail(Bitmap original, int idealWidth, int idealHeight, SPFolder folder, string fileName)
  SPFile file = null;

  Assembly userProfilesAssembly = typeof(UserProfile).Assembly;

  Type userProfilePhotosType = userProfilesAssembly.GetType("Microsoft.Office.Server.UserProfiles.UserProfilePhotos");
  MethodInfo [] mi_methods = userProfilePhotosType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static);

  MethodInfo mi_CreateThumbnail = mi_methods[0];
  if (mi_CreateThumbnail != null)
    file = (SPFile)mi_CreateThumbnail.Invoke(null, new object[] { original, idealWidth, idealHeight, folder, fileName, null });

  return file;
} // end of function

/// Update User Profile Property
private void SetPictureUrl(string accountName, SPFolder subfolderForPictures, UserProfile userProfile)
  string account = accountName.Substring(0, accountName.IndexOf("_")) + "\\" + accountName.Substring(accountName.IndexOf("_") + 1);

  string pictureUrl = String.Format("{0}/{1}/{2}_MThumb.jpg", subfolderForPictures.ParentWeb.Site.Url, subfolderForPictures.Url, accountName);

  userProfile["PictureUrl"].Value = pictureUrl;
} // end of function

12 thoughts on “Upload User Profile Pictures Programmatically – SharePoint 2013

  1. Came across your submit on DSLR Photography and thought it shared some quite useful insight on this topic.
    What ever your encounter with digital photography there is some thing for
    everyone to consider away from this submit. Thank you quite considerably and I
    search forward to your following submit

  2. Pingback: Nishant Rana

  3. Excellent pieces. Keep posting such kind of info on your site.
    Im really impressed by your site.
    Hey there, You’ve performed a great job. I will definitely digg it
    and in my view suggest to my friends. I’m sure they will
    be benefited from this web site.

  4. I’m impressed, I must say. Really rarely do I encounter a blog that’s both educative and entertaining, and let me tell you, you have hit the nail on the head. Your idea is outstanding; the issue is something that not enough people are speaking intelligently about. I am very happy that I stumbled across this in my search for something relating to this.

  5. Pingback: Study Guide for Exam 70-489 - Developing Microsoft SharePoint Server 2013 Advanced Solutions – wiliammbr's blog

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 )

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