Resize Images To Thumbnails in .NET

By Robbe D. Morris

Printer Friendly Version

Robbe Morris
Robbe & Melisa Morris
At the time of this writing, my son is now 3 weeks old.  One of the unknown challenges I've run into is how to put all the pictures of him up on the web for my relatives that live so far way in the shortest amount of time possible.  So, I opted to write this little page in ASP.NET for use on my wife's website that will go through a given folder and create a thumbnail version of every .jpg, .gif, and .bmp it finds (assuming the folder in the querystring parameter has write permissions granted to the IUSR_machinename account).  The page can also take another querystring parameter and use it to generate a nicely formatted HTML page and TABLE displaying the thumbnails with links to the original image.


View Thumbnail Demonstration
 
The main method that creates the thumbnail is called GenerateThumbNail.  The rest of the code is pretty basic.  As you'll see, it isn't rocket science but I thought share the results of my work to demonstrate how to do it.  Feel free to take the sample and adjust it as needed for both commerical or personal use.
 
Source Code For ImageWriter.aspx
  
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Text" %>
 

<script Language="C#" runat="server">
 
           
  protected Size ThumbNailSize = new Size(75,75);
  protected string ThumbNailName = "_thumbnail";

  private void Page_Load(object sender, System.EventArgs e)
  {
      if (RequestObject("generate") == "1")
      {
         GenerateThumbNailImagesForFolder(RequestObject("imgfolder")); 
      }
       this.RW(GenerateHTMLPageForFolder(RequestObject("imgfolder")));
  }

       

        public void GenerateThumbNailImagesForFolder(string FolderName)
        {
             string sPhysicalPath="";
             string sFileName="";
             string sThumbName="";
 
             sPhysicalPath = Server.MapPath(FolderName);

             DirectoryInfo oDir = new DirectoryInfo(sPhysicalPath);
  
            try
            {

                  FileInfo[] oDeleteFiles = oDir.GetFiles();

                  foreach (FileInfo oFile in oDeleteFiles)
                  {                   
                     sFileName = oFile.Name.ToLower(); 
                     if (sFileName.IndexOf("thumbnail") > 0) { oFile.Delete(); }
                   }

                   FileInfo[] oFiles = oDir.GetFiles();

                   foreach (FileInfo oFile in oFiles)
                  {

                      sFileName = oFile.Name.ToLower(); 

                      sThumbName = sFileName.Replace(".",this.ThumbNailName + "."); 

                      if (sFileName.IndexOf(".gif") > 0)
                      { 
                         this.GenerateThumbNail(sPhysicalPath,sFileName,sThumbName,ImageFormat.Gif); 
                      }
                      if (sFileName.IndexOf(".jpg") > 0)
                      { 
                         this.GenerateThumbNail(sPhysicalPath,sFileName,sThumbName,ImageFormat.Jpeg); 
                      }
                      if (sFileName.IndexOf(".bmp") > 0)
                     { 
                        this.GenerateThumbNail(sPhysicalPath,sFileName,sThumbName,ImageFormat.Bmp); 
                     }

                   }
           }
          catch (Exception) { }
        }

     public void GenerateThumbNail(string sPhysicalPath,string sOrgFileName,
                                                                string sThumbNailFileName,ImageFormat oFormat)
       {

            try
            {
                 
                   System.Drawing.Image oImg = System.Drawing.Image.FromFile(sPhysicalPath + @"\" + sOrgFileName); 

                   System.Drawing.Image oThumbNail = new Bitmap(this.ThumbNailSize.Width, 
                                                                                                                 this.ThumbNailSize.Height, oImg.PixelFormat);

                   Graphics oGraphic =  Graphics.FromImage(oThumbNail);

                   oGraphic.CompositingQuality = CompositingQuality.HighQuality ;

                   oGraphic.SmoothingMode = SmoothingMode.HighQuality ;

                   oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic ;

                   Rectangle oRectangle = new Rectangle(0, 0, this.ThumbNailSize.Width, this.ThumbNailSize.Height);

                   oGraphic.DrawImage(oImg, oRectangle);
              
                   oThumbNail.Save(sPhysicalPath + @"\" + sThumbNailFileName,oFormat); 
				  
                   oImg.Dispose(); 

            }
            catch (Exception)  { }

       }

        public string GenerateHTMLPageForFolder(string FolderName)
        {

           string sPhysicalPath="";
           string sFileName="";
           int nFound=0;
           int nCol=0;
           int nMaxCols=7;

           StringBuilder oString = new StringBuilder();

           oString.Append("<html><body><table border="0" cellspacing="2" cellpadding="2" width='80%' align="center">");
           
            try
            {

                 sPhysicalPath = Server.MapPath(FolderName);
                 DirectoryInfo oDir = new DirectoryInfo(sPhysicalPath);
                 FileInfo[] oFiles = oDir.GetFiles();

                  foreach (FileInfo oFile in oFiles)
                  {                   

                     sFileName = oFile.Name.ToLower(); 
                     nFound++;

                     if (sFileName.IndexOf("thumbnail") > 0)
                     { 

                       nCol++;
                       if (nCol == 1) { oString.Append("<tr>"); }

                        if ((sFileName.IndexOf(".gif") > 0) || (sFileName.IndexOf(".jpg") > 0) || (sFileName.IndexOf(".bmp") > 0))
                        {
                           oString.Append("<td align="left">");
                           oString.Append("<a href=" + FolderName + "/" + sFileName.Replace(this.ThumbNailName,""));
                           oString.Append(" >"); 
                           oString.Append("<img src=" + FolderName + "/" + sFileName + " border="0">");
                           oString.Append("</a>");
                           oString.Append("</td>");
                        }

                        if (nCol == nMaxCols) { nCol = 0; oString.Append("</tr>"); }

                      }

                   }

                  if ((nFound >0) && (nCol < nMaxCols))
                  {
                     nCol = nMaxCols - nCol;
                     oString.Append("<td colspan=" + nCol.ToString() + "> </td></tr>");
                  }

             }
             catch (Exception) {  }

             oString.Append("</table></body></html>");

             return oString.ToString();

        }

        public void RW(string sVal)
        {  
          Response.Write(sVal +'\n');
        } 

        public string RequestObject(string sName)
        {
          string sRet="";
          try { sRet = Request[sName].ToString().Trim(); }
          catch (Exception) { sRet = "";}  
          return sRet;
        }
</script>

Robbe has been a Microsoft MVP in C# since 2004.  He is also the co-founder of NullSkull.com which provides .NET articles, book reviews, software reviews, and software download and purchase advice.