Minggu, 23 Januari 2011

Very Simple .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);
}
}
}

Update: A couple of folks asked me about how to do this in ASP.NET... Bertrand has a much more complete example of that here:


http://dotnetslackers.com/articles/aspnet/Generating-Image-Thumbnails-in-ASP-NET.aspx


http://weblogs.asp.net/bleroy/archive/2007/12/05/what-interpolationmode-and-compositingquality-to-use-when-generating-thumbnails-via-system-drawing.aspx



Tidak ada komentar: