Search This Blog

Monday, August 2, 2010

C# Code To make thumbnails of full size images

This is to written in fileupload code behind 
 
   1:   if (FileUpload4.FileName != "")
   2:     {
   3:        string appPath = Request.PhysicalApplicationPath;
   4:        path = appPath + "Images\\" + FileUpload4.FileName;
   5:        path6 = "Images/Thumbnail/" + FileUpload4.FileName;
   6:   FileUpload4.SaveAs(Server.MapPath("../Images/" + FileUpload4.FileName));
   7:   
   8:  System.Drawing.Image ImageToSave = resizeImage(System.Drawing.Image.FromStream(FileUpload4.FileContent), new Size(150, 150));
   9:                  // supply actual image to the function 
  10:                  ImageToSave.Save(Server.MapPath(System.IO.Path.Combine("../Images/Thumbnail/", FileUpload4.FileName)));
  11:                  // the function returns a thumbnail which is saved here 
  12:   
  13:  }
 
This is drawing function that is place below above code
   1:   private static System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size)
   2:    {
3: int sourceWidth = imgToResize.Width;
   4:          int sourceHeight = imgToResize.Height;
   5:          float nPercent = 0;
   6:          float nPercentW = 0;
   7:          float nPercentH = 0;
   8:   
   9:         nPercentW = ((float)size.Width / (float)sourceWidth);
  10:         nPercentH = ((float)size.Height / (float)sourceHeight);
  11:   
  12:              if (nPercentH < nPercentW)
  13:                  nPercent = nPercentH;
  14:              else
  15:                  nPercent = nPercentW;
  16:   
  17:           int destWidth = (int)(sourceWidth * nPercent);
  18:           int destHeight = (int)(sourceHeight * nPercent);
  19:   
  20:           Bitmap b = new Bitmap(destWidth, destHeight);
  21:          Graphics g = Graphics.FromImage((System.Drawing.Image)b);
  22:          g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  23:   
  24:          g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
  25:          g.Dispose();
  26:   
  27:              return (System.Drawing.Image)b;
  28:          }
namespace to be included
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
 
 
 
 

No comments:

Post a Comment