Upload Image and Create Thumbnail

In this post, I will show an implementation of uploading image to server and creating a thumbnail version of the uploaded image. Creating a thumbnail is useful as it reduces image size and dimensions and improves application’s performance.

In your ASP.NET Controller’s HttpPost Action, you can get the uploaded image file as HttpPostedFileBase as:


HttpPostedFileBase file = Request.Files[0];

You can also check for the file’s ContentLength property to make sure the uploaded image is within certain allowed size range:


if (file.ContentLength > 20000000)//less than 2 mb
{
return Json(new { ErrorMessage = "Please upload an image of size smaller than 2 MB." }, JsonRequestBehavior.AllowGet);
}

When uploading an image, one important thing to keep in mind is the filename of the uploaded image. You want to be sure that you do not replace an existing file with the newly uploaded file. So, I usually rename the uploaded image to a unique filename.


string fname = file.FileName;
var extension = Path.GetExtension(fname);

string newFname = Guid.NewGuid().ToString();
var newFileName = newFname + extension;

Now, save the uploaded image to any specified folder like this:


// Get the complete folder path and store the file inside it.
newFileName = Path.Combine(Server.MapPath("~/Uploads/"), newFileName);
file.SaveAs(newFileName);

Next, create a file name for the thumbnail version of the image.


var thumbVersionFileName = newFname + "_thumb" + extension;

thumbVersionFileName = Path.Combine(Server.MapPath("~/Uploads/"), thumbVersionFileName);

Now to get the actual thumbnail size version, use the function below:


public static void CreateThumbnailImageVersion(string imagePath, int xSize, int ySize, string returnImagePath)
{
Image image = Image.FromFile(imagePath);
Image thumb = image.GetThumbnailImage(xSize, ySize, () => false, IntPtr.Zero);
thumb.Save(returnImagePath);

image.Dispose();
}

Tags: