Reader Level:

Fetching Image from SharePoint 2007 picture library using object model

By Dhananjay Kumar on Feb 08, 2011
Fetch an image from a SharePoint 2007 picture library and bind to a System.Drwaing.Image object
  • 0
  • 0
  • 12081

I thought it would be an easy requirement to fetch an image from a SharePoint 2007 picture library and bind to a System.Drwaing.Image object. But when I started doing that, I had to give myself 3 to 4 hours. So here is the code snippet to fetch images from a SharePoint 2007 picture library.

Namespace Required


Function to return Image as MemoryStream

This function will return an image from a SharePoint 2007 picture library using WSS Object model. This function is taking siteUrl and filename to be fetched from the picture library. This function is returning a MemoryStream.

public static MemoryStream GetImageforCharts(string siteUrl, string fileName)
            Byte[] fileContentsArray=null;
            MemoryStream imageStream = null;
                using (SPSite site = new SPSite(siteUrl))
                // using (SPSite site = SPContext.Current.Site)
                    using (SPWeb web = site.OpenWeb())
                        SPPictureLibrary chartPictureLibrary = (SPPictureLibrary)web.Lists["UrPictureLibraryName"];
                        SPQuery query = new SPQuery();
                        query.Query = @"<Where><Eq><FieldRef Name ='Title'/><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
                        SPListItemCollection lstImages = chartPictureLibrary.GetItems(query);
                        foreach (SPListItem r in lstImages)
                            SPFile file = r.File;
                            using (Stream fileContents = file.OpenBinaryStream())
                                long  length = fileContents.Length ;
                                fileContentsArray = new Byte[length];
                                fileContents.Read(fileContentsArray, 0,Convert.ToInt32(length));



                imageStream = new MemoryStream(fileContentsArray);
                return imageStream;

            catch (Exception ex)
                return null;

Using the Function

Now we can call the function as below, and save the image in a System.Drawing.Image object.


Dhananjay Kumar

Dhananjay kumar is an independent trainer, a consultant and a programmer from India. He has mentored more than 1000 professionals and known for his unique way of teaching. He has been part of the multiple projects for bi... Read more

Personal Blog:

Trending up