Skip to content

Instantly share code, notes, and snippets.

@dredix
Created July 23, 2012 07:34
Show Gist options
  • Save dredix/3162433 to your computer and use it in GitHub Desktop.
Save dredix/3162433 to your computer and use it in GitHub Desktop.
A C# console program that creates square 150x150 thumbnails for all the images in a given folder, preserving the directory structure
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
namespace Thumbinate
{
class Program
{
static int Main(string[] args)
{
var sw = new Stopwatch();
sw.Start();
Console.WriteLine("Thumbinate started at {0:yyyy-MM-dd HH:mm:ss.ffff}", DateTime.Now);
try
{
return Run(args);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
return 1;
}
finally
{
sw.Stop();
Console.WriteLine("Thumbinate finished. Elapsed time: {0}", sw.ElapsedMilliseconds);
}
}
static int Run(string[] args)
{
if (args.Length < 2) return Syntax();
if (!Directory.Exists(args[0])) return Syntax();
var source = new DirectoryInfo(args[0]);
var target = Directory.Exists(args[1]) ? new DirectoryInfo(args[1]) :
Directory.CreateDirectory(args[1]);
var source_len = source.FullName.Length;
var files = source.GetFiles("*.jpg", SearchOption.AllDirectories);
foreach (var file in files)
{
try
{
var dest_folder = Path.Combine(target.FullName, file.DirectoryName.Substring(source_len).TrimStart('\\'));
if (!Directory.Exists(dest_folder))
{
Console.WriteLine("Creating folder {0}", dest_folder);
Directory.CreateDirectory(dest_folder);
}
var destination = Path.Combine(dest_folder, file.Name);
if (!File.Exists(destination))
{
using (var bitmap = new Bitmap(file.FullName))
{
int newWidth = 150, newHeight = 150;
int offsetWidth = 0, offsetHeight = 0;
if (bitmap.Height < bitmap.Width)
{
newWidth = (int)((double)bitmap.Width * 150d / (double)bitmap.Height);
offsetWidth = (newWidth - 150) / 2;
}
else
{
newHeight = (int)((double)bitmap.Height * 150d / (double)bitmap.Width);
offsetHeight = (newHeight - 150) / 2;
}
var cropRect = new Rectangle(offsetWidth, offsetHeight, 150, 150);
using (var new_bitmap = new Bitmap(bitmap, newWidth, newHeight))
{
var cloned = new_bitmap.Clone(cropRect, bitmap.PixelFormat);
cloned.Save(destination);
cloned.Dispose();
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine("{0}:: {1}", file.FullName, ex.Message);
}
}
return 0;
}
static int Syntax()
{
Console.Error.WriteLine("Invalid arguments.\r\nSyntax: Thumbinate source_folder target_folder");
return 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment