Tuesday, March 21, 2006

Creating thumbnails in ASP.NET

.NET makes some things really easy and creating thumbnail images for a website is one of them. Here's the code I'm using on one of my websites.
 private void CreateThumbnail(string fileName)
 {
   string physicalThumbFileName =
     Path.GetDirectoryName(Page.Request.PhysicalPath) +
     "\\images\\" + fileName + "_thumb.jpg";
   if (!File.Exists(physicalThumbFileName))
   {
     // create thumbnail
     using (Bitmap img = new Bitmap(ImageFileName(fileName)))
     {
       using (Bitmap smaller = new Bitmap(img,
         new Size((img.Width*120)/img.Height, 120)))
       {
         smaller.Save(physicalThumbFileName, ImageFormat.Jpeg);
       }
     }
   }
 }
The thumbnails are created when the page needs them, thus simplifying the upload process, since there's no need for any manual thumbnail creation.

No comments: