Skip to content

Instantly share code, notes, and snippets.

@trevorhreed
Created October 23, 2015 18:30
Show Gist options
  • Save trevorhreed/0160d347b5348e73a4d2 to your computer and use it in GitHub Desktop.
Save trevorhreed/0160d347b5348e73a4d2 to your computer and use it in GitHub Desktop.
Thumbnail Maker
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace ThumbnailGenerator
{
class Hammer
{
private static string SOURCE_DIRECTORY = "Source directory";
private static string TARGET_DIRECTORY = "Target directory";
private static string FILENAME_PATTERN = "Filename pattern";
private static string FILENAME_FORMAT = "Filename format";
private static string THUMBNAIL_WIDTH = "Thumbnail width";
public static void Main(string[] args)
{
Dictionary<string, string> prompts = new Dictionary<string, string>()
{
{ SOURCE_DIRECTORY, Directory.GetCurrentDirectory() },
{ TARGET_DIRECTORY, Directory.GetCurrentDirectory() },
{ FILENAME_PATTERN, @"^(.*)\.(.*)$" },
{ FILENAME_FORMAT, "{0}_thumbnail.{1}" },
{ THUMBNAIL_WIDTH, "200" }
};
try {
Console.WriteLine("Welcome to Hammer!\nThis utility will help you create thumbnails from larger images.");
List<string> keys = new List<string>(prompts.Keys);
foreach (string key in keys) {
Console.Write("\n" + key + ": (" + prompts[key] + ") ");
string value = Console.ReadLine();
if (string.IsNullOrEmpty(value)) continue;
prompts[key] = value;
}
HammerDirectory(
prompts[SOURCE_DIRECTORY],
prompts[TARGET_DIRECTORY],
prompts[FILENAME_PATTERN],
prompts[FILENAME_FORMAT],
int.Parse(prompts[THUMBNAIL_WIDTH])
);
}
catch (FormatException)
{
Console.WriteLine("Your file name pattern does not match your file name format (pattern: '" + prompts[FILENAME_PATTERN] + "', format: '" + prompts[FILENAME_FORMAT] + "').");
}
catch (Exception ex)
{
string innerException = ex.InnerException != null ? ex.InnerException.Message : "No inner exception";
Console.WriteLine("Exception: " + ex.Message + " (" + innerException + ").");
}
Console.ReadKey(true);
}
public static void HammerDirectory(string sourceDir, string targetDir, string fileNamePattern, string fileNameFormat, int newWidth)
{
if (sourceDir == null || !Directory.Exists(sourceDir)) sourceDir = Directory.GetCurrentDirectory();
if (targetDir == null || !Directory.Exists(targetDir)) targetDir = sourceDir;
if (fileNamePattern == null) fileNamePattern = @"^(.*)\.(.*)$";
if (fileNameFormat == null) fileNameFormat = "{0}_thumb.{1}";
if (newWidth < 32) newWidth = 32;
ImageAttributes imgAttrs = new ImageAttributes();
imgAttrs.SetWrapMode(WrapMode.TileFlipXY);
Regex fileNameRegex = new Regex(fileNamePattern);
IEnumerable<string> files = Directory
.GetFiles(sourceDir, "*.*", SearchOption.TopDirectoryOnly)
.Where(path => fileNameRegex.IsMatch(path));
foreach (string file in files)
{
string newFileName = GetNewFileName(file, targetDir, fileNameRegex, fileNameFormat);
Bitmap thumbnail = GetThumbnail(file, newWidth, imgAttrs);
thumbnail.Save(newFileName);
}
}
private static string GetNewFileName(string originalFileName, string targetDir, Regex fileNameRegex, string fileNameFormat)
{
string fileName = originalFileName.Substring(originalFileName.LastIndexOf(Path.DirectorySeparatorChar) + 1);
object[] fileNameFormatArgs = fileNameRegex.Match(fileName).Groups.Cast<Capture>().Skip(1).Select(c => c.Value).ToArray();
return Path.Combine(targetDir, string.Format(fileNameFormat, fileNameFormatArgs));
}
private static Bitmap GetThumbnail(string originalFileName, int newWidth, ImageAttributes imgAttrs)
{
Image original = Image.FromFile(originalFileName);
int newHeight = (int)((float)original.Height * ((float)newWidth / (float)original.Width));
Bitmap target = new Bitmap(newWidth, newHeight);
Graphics copier = Graphics.FromImage(target);
copier.InterpolationMode = InterpolationMode.HighQualityBicubic;
copier.CompositingQuality = CompositingQuality.Default;
copier.CompositingMode = CompositingMode.SourceCopy;
Rectangle thumbRect = new Rectangle(0, 0, newWidth, newHeight);
copier.DrawImage(original, thumbRect, 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, imgAttrs);
return target;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment