ASP.NET uploaded images as thumbnails

A short piece of code showing how to accept a HTTP upload of a JPG and save it with different dimensions.

//First the code to accept the image
private void UploadImageButtonClick(object sender, System.EventArgs e)
    System.Web.HttpFileCollection allUploadedFiles = System.Web.HttpContext.Current.Request.Files;
    if (allUploadedFiles.Count == 0)
      throw new Exception("No files uploaded");
    if (allUploadedFiles.Count > 1)
      throw new Exception("Too many files uploaded");

    System.Web.HttpPostedFile uploadedFile = allUploadedFiles.Get(0);
    String fileName = Path.GetFileName(uploadedFile.FileName);
    String fileExt = Path.GetExtension(fileName);
    if (fileExt.ToLower() != ".jpg")
      throw new Exception("File is not a JPG image");

    String newFileName = Server.MapPath("uploaded/images") + "\\" + fileName;
    if (File.Exists(newFileName))
      throw new Exception(fileName + " already exists, you must delete it first");

    System.Drawing.Image image = CreateThumbnailImage(uploadedFile);
    ImageCodecInfo encoder = FindCodecInfo("JPEG");
    EncoderParameters encoderParameters = new EncoderParameters();

    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 25L);
    image.Save(newFileName, encoder, encoderParameters);
  catch (Exception error)
    //Handle accordingly

//Next the code to find the image encoder
private ImageCodecInfo FindCodecInfo(String description)
  ImageCodecInfo[] encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
  foreach (ImageCodecInfo encoder in encoders)
    if (encoder.FormatDescription == description)
      return encoder;
  return null;

//Now the code to resize + save
private System.Drawing.Image CreateThumbnailImage(HttpPostedFile file)
  System.Drawing.Image source;
  System.Drawing.Image result;
  Double xRatio;
  Double yRatio;
  Int32 newWidth;
  Int32 newHeight;

  source = System.Drawing.Image.FromStream(file.InputStream);

  xRatio = 150.0 / source.Width;
  yRatio = 150.0 / source.Height;
  if (xRatio < yRatio)
    yRatio = xRatio;
    xRatio = yRatio;

  newWidth = (Int32)System.Math.Round(source.Width * xRatio);
  newHeight = (Int32)System.Math.Floor(source.Height * yRatio);

  result = source.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
  return result;


Share this article!

Follow us!

Find more helpful articles: