SharePoint: Build a Webpart to Resize and Upload Images to a Picture Library

SharePoint: Build a Webpart to Resize and Upload Images to a Picture Library

Introduction

Uploading a file to SharePoint in a custom webpart is very easy; as simple example involves adding an asp:FileUpload control to your webpart and adding a button to click on (to upload the selected file!).

In this article we're going to create a visual webpart that allows a user to upload an image to SharePoint. During the upload process, the image dimensions are checked, and if the image's width or height exceeds 300px, we'll resize the image so that the maximum width/height do not exceed 300px. The resizing process will keep the images width/height ratio the same as the original image selected. After uploading the image to SharePoint, we'll display the image on the page in an asp:image control.

Visual Webpart Example

1. Open Visual Studio (this example has been created in Visual Studio 2012)
2. Create a new farm scoped Empty SharePoint project
3. Add a new visual webpart to the project
4. Add the following additional references to the project

System.Core
System.Drawing

5. Add the following using statements

using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;


6. In the visual webparts ascx file, add the following markup to the page

<SharePoint:CssLink runat="server" ID="mycorestyles" DefaultUrl="/_layouts/incestyles/core.css"></SharePoint:CssLink>
<div class="container">
    <div class="row">
        <div class="span8 rowpad">
            <span>Click browse to locate a file to upload, then click Upload to save it to SharePoint.</span>
        </div>
    </div>
    <div class="row">
        <div class="span8 rowpad">
            <asp:Label ID="userMessage" runat="server" Text=""></asp:Label>
        </div>
    </div>
    <div class="row">
        <div class="span8 rowpad">
            <asp:FileUpload ID="fileBrowser" runat="server" />
            <asp:Button ID="uploadFile" runat="server" Text="Upload" OnClick="UploadFileClick" />
        </div>
    </div>
    <div class="row">
        <asp:Image ID="previewImage" runat="server" Visible="false" />
    </div>
</div>


In the above markup, I've put a CSS reference to a stylesheet I'm using for formatting the page (incidentally, that stylesheet is based on Twitters Bootstrap).

The webpart will look like this when it loads;

...and like this after you upload an image (hopefully with a different picture!)

7. In the visual webparts code file, add the following code (the OnClick event and two helper methods for resizing the image). In the uploadFile button's OnClick event, we check a file has been selected, is in the right format, and is within size restrictions, before finally uploading it to a memory stream. Once we have the image as a memory steam, we can resize the image to our required width/height maximums (if the selected image has exceeded our maximums width/height).

Note that elevating permissions, error handling and validation have been omitted to keep the example short.

protected void UploadFileClick(object sender, EventArgs e)
{
    try
    {
        userMessage.Text = String.Empty;
        SPWeb web = SPContext.Current.Site.RootWeb;
        previewImage.ImageUrl = null;
        previewImage.Visible = false;
        if (!fileBrowser.HasFile)
        {
            userMessage.Text = "Please select a file before clicking upload.";
            return;
        }
        //Check the file is less than 4MB
        int fileSize = fileBrowser.PostedFile.ContentLength;
        if (fileSize > 4000000)
        {
            userMessage.Text += String.Format("File Size Exceeds 4MB. Choose a smaller file.");
            return;
        }
  
        String imageFileExtension = Path.GetExtension(fileBrowser.FileName);
        //Check the user has selected a jpg image
        if (imageFileExtension == null || imageFileExtension.ToLower() != ".jpg")
        {
            userMessage.Text += "The file you have selected is not in the right format. Please use a jpg image.";
            return;
        }
  
        var imageFileData = fileBrowser.FileBytes;
        using (var imageFileStream = new MemoryStream())
        {
            imageFileStream.Write(imageFileData, 0, imageFileData.Length);
            //Before uploading the image to SharePoint, lets make sure resize the image if the width or height are greater than 300px.
            var imagePreview = ResizeImage(imageFileStream, 300, 300);
            SPList listExists = web.Lists.TryGetList("picturelibrary");
            SPUtility.ValidateFormDigest();
            if (listExists == null)
            {
                //...
                return;
            }
            try
            {
                var fileName = fileBrowser.FileName.Replace(" ", "-");
                var urlpreview = String.Format("{0}/picturelibrary/{1}", web.Url, fileName);
                web.AllowUnsafeUpdates = true;
                web.Files.Add(urlpreview, imagePreview, true);
                previewImage.ImageUrl = urlpreview;
                previewImage.Visible = true;
            }
            catch (Exception exception)
            {
                //..Do something
            }
        }
    }
    catch (Exception exception)
    {
        //...
    }
}
  
public byte[] ResizeImage(Stream fileData, int maxwidth, int maxheight)
{
    using (var image = new Bitmap(fileData))
    {
        int adjustedWidth = image.Width;
        int adjustedHieght = image.Height;
          
        //Check the image is less than the maxwidth. If not, resize the image dimensions.
        if (adjustedWidth > maxwidth)
        {
            decimal ratio = Decimal.Divide(maxwidth, adjustedWidth);
            adjustedWidth = maxwidth;
            adjustedHieght = Convert.ToInt32(Decimal.Multiply(adjustedHieght, ratio));
        }
        //Now that we've adjusted the width, check the hieght is below the maximum hieght value
        if (adjustedHieght > maxheight)
        {
            decimal ratio = Decimal.Divide(maxheight, adjustedHieght);
            adjustedHieght = maxheight;
            adjustedWidth = Convert.ToInt32(Decimal.Multiply(adjustedWidth, ratio));
        }
  
        var resizedImage = new Bitmap(adjustedWidth, adjustedHieght);
        var g = Graphics.FromImage(resizedImage);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.FillRectangle(Brushes.White, 0, 0, adjustedWidth, adjustedHieght);
        g.DrawImage(image, 0, 0, adjustedWidth, adjustedHieght);
        var ms = new MemoryStream();
        const int quality = 90;
        var encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)quality);
        resizedImage.Save(ms, GetImageCodeInfo("image/jpeg"), encoderParameters);
        ms.Position = 0;
        var data = new byte[ms.Length];
        ms.Read(data, 0, (int)ms.Length);
        return data;
    }
}
  
public static ImageCodecInfo GetImageCodeInfo(string mimeType)
{
    ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
    foreach (ImageCodecInfo imageCodeInfo in imageEncoders)
    {
        if (imageCodeInfo.MimeType.Equals(mimeType, StringComparison.OrdinalIgnoreCase))
            return imageCodeInfo;
    }
    return null;
}


See Also

Another important place to find a huge amount of SharePoint related articles is the TechNet Wiki itself. The best entry point is SharePoint Resources on the TechNet Wiki

References

Sort by: Published Date | Most Recent | Most Useful
Comments
Page 1 of 1 (9 items)