Creating high quality thumbnail image in C#

Posted by SheoNarayan under C# category on | Points: 40 | Views : 11203
Below is the tested and proven code snippet to created high quality thumbnail images from the file being uploaded to the server.

You need to use following namespaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

I am assuming that you will have a FileUpload control in aspx page, keep this code into the click event of your button
System.Drawing.Image imgToResize = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
string path = Server.MapPath("~/") + DateTime.Now.Ticks.ToString().Substring(5) + ".jpg";
ResizeAndSaveHighQualityImage(imgToResize, 140, 105, path, 100)

// This is the function you need to call and pass Image to resize, width and height of the resized image, path to save and quality you want to maintain while resizing.
/// <summary>
/// Resize and save high quality image
/// </summary>
/// <param name="image"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="pathToSave"></param>
/// <param name="quality"></param>
public static void ResizeAndSaveHighQualityImage(System.Drawing.Image image, int width, int height, string pathToSave, int quality)
// the resized result bitmap
using (Bitmap result = new Bitmap(width, height))
// get the graphics and draw the passed image to the result bitmap
using (Graphics grphs = Graphics.FromImage(result))
grphs.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
grphs.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
grphs.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
grphs.DrawImage(image, 0, 0, result.Width, result.Height);

// check the quality passed in
if ((quality < 0) || (quality > 100))
string error = string.Format("quality must be 0, 100", quality);
throw new ArgumentOutOfRangeException(error);

EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
string lookupKey = "image/jpeg";
var jpegCodec = ImageCodecInfo.GetImageEncoders().Where(i => i.MimeType.Equals(lookupKey)).FirstOrDefault();

//create a collection of EncoderParameters and set the quality parameter
var encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
//save the image using the codec and the encoder parameter
result.Save(pathToSave, jpegCodec, encoderParams);

Hope this will help someone.


Comments or Responses

Login to post response