15 February, 2009

Asp.NET Thumbnail Creation Code

When I was working the update for my Ajax demo, I needed to create thumb nail from a director of photos. There are tons of tools out there to do this, but I thought I'd share the very simple code I used.

It takes all the jpgs in the root path and creates 160x120 thumbnails of them. It also copies the original photo into fullpath.

namespace ThumbNailer
{
class Program
{
static void Main(string[] args)
{
string rootPath = @"C:\Users\brada\Desktop\ForDemo";
string thumbPath = Path.Combine(rootPath, "Thumb");
if (Directory.Exists(thumbPath)) DirectoryDelete(thumbPath);
Directory.CreateDirectory(thumbPath);

int imageNumber = 0;
foreach (string s in Directory.GetFiles(rootPath, "*.jpg"))
{
imageNumber++;
Console.WriteLine("{0}:{1}", imageNumber, s);
Image i = Image.FromFile(s);
Image thumb = i.GetThumbnailImage(160, 120, null, IntPtr.Zero);
thumb.Save(Path.Combine(thumbPath, GetName(imageNumber)));
}
}

static void DirectoryDelete(string directoryName)
{
foreach (string filename in Directory.GetFiles(directoryName))
{
File.Delete(filename);
}
Directory.Delete(directoryName);
}
static string GetName(int imageNumber)
{
return String.Format("{0}.jpg", imageNumber);
}
}
}

No comments: