Thursday, June 30, 2011

Creating Thumbnails C#

I was creating a website for a friend, and the photo gallery I decided to use needed thumbnails of all the pictures she had given me.  Now rather than do this by hand, or try and use the uploader I made on the site that can only handle three pictures at a time, I decided to make a program to do this for me.
First I create a folder in the path that was specified by the user, the string folder.  Then iterate on each file that is in the directory.
Directory.CreateDirectory(Path.Combine(folder, "thumbs"));
foreach (string pic in Directory.GetFiles(folder))
{
switch (Path.GetExtension(pic.ToLower()))
{
              case ".jpg": break;
case ".bmp": break;
case ".gif": break;
case ".exif": break;
case ".png": break;
case ".tiff": break;
default: // not a recognized format by
//System.Drawing.Bitmap so skip and go to the next
continue;
}
//more code to follow

I do some funky things to calculate the width and height that gets the images sized down to the way I want them.  I don’t think it’s really important and if you’re trying to implement this you should feel free to calculate the ratio any way you like.   Next, I create an empty bitmap to the height and width I want.  Then use the graphics class to load in the bitmap.  The settings SmoothingMode,  InterpolationMode, and PixelOffsetMode are all ones I found to keep the thumbnail looking good.  The last call with the graphics class, DrawImage is loading the image you want to resize onto the bitmap previously set up, shrinking it to fit, give you a nice thumbnail in memory.  The last thing to do is write the image to disc.  You can see in the code, I place the thumbnail in the thumbs directory previously created and use the name of the original file with thumb- prepended to the name.

using (Bitmap newImage = new Bitmap(newWidth, newHeight))
{
using (Graphics gr = Graphics.FromImage(newImage))
       {
              gr.SmoothingMode = SmoothingMode.AntiAlias;
              gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
              gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
              gr.DrawImage(new Bitmap(pic), new Rectangle(0, 0, newWidth, newHeight));
}

       string imgName = Path.GetFileName(pic); //get the images name
       //write the image to thumbs directory with the thumb-imageName
       newImage.Save(Path.Combine(folder, "thumbs\\thumb-" + imgName));
}
} //end foreach

That’s really all there is to it folks.  If you for some reason need to create a bunch of thumbnails and don’t want to implement it yourself, here is the executable I created, along with the source.