A windows command line application to resize images in a directory

by Kevin Bosch 24. August 2010 20:16

I came across a need to resize a whole bunch of images. So I decided to write a little console application in .NET to do the work for me. With 100’s of images to resize it was worth the effort in creating a little application to do the job for me. CA.Console.ResizeImage.exe is what I came up with the source code is listed in this post

CA.Console.ResizeImage.exe is a command line windows utility that resizes the following supported images "jpeg,gif,bmp,png" in a given directory to a maximum size keeping the aspect ratio. It is possible to configure the source, destination and maximum size of the images via config file or command line switches it also has some default options for click and go solution. You can download the ziped binary and config file CA.Console.ResizeImage.exe.zip (4.69 kb).

In the simplest case, you can just copy CA.Console.ResizeImage.exe into the directory of your images and double click on it. It will then generate new images with the same name into a folder called ResizedImages without any configuration it will resize all images to 500 x 500 adjust height or width accordingly to keep aspect ratio.

There are two ways to override the default configuration values.

via the CA.Console.ResizeImage.exe.config file


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key ="ImageMaxWidthpx" value ="500"/>
    <add key ="ImageMaxHeightpx" value ="500"/>
    <add key ="SourceImagesDirectory" value =""/>
    <add key ="ResizedImagesDirectory" value =""/>
  </appSettings>
</configuration>

When using the config file you need to keep the config file and the executable together. The parameters are easy to follow. The only thing to note is that the directories must exist else the application will default back to the defaults.

via command line parameters

C:\>CA.Console.ResizeImage.exe "-s:c:\SourceImageDirectory" "-d:c:\ResizeImageDirectoty" "-h:100" "-w:100"

where

  • -s: is the directive for the source directory
  • -d: is the directive for the Resize Image Directoty
  • -h: is the directive for the max height
  • -w: is the directive for the max width

If any of the parameters are missing then the default values will be taken. It will try use the values in the config file and if they are missing they will use the hard coded values

Source code this is a standard .NET console application with 3 files, program.cs and ResizeImageLib.cs are list below and app.config is listed above

Program.cs

using System.Configuration;
using System.Diagnostics;
using System.IO;

namespace CA.Console.ResizeImage
{
    class Program
    {
        private const string FIELD_CONFIGKEY_SOURCEIMAGE_DIR = "SourceImagesDirectory";
        private const string FIELD_CONFIGKEY_RESIZEDIMAGE_DIR = "ResizedImagesDirectory";
        private const string FIELD_CONFIGKEY_IMAGEMAXWIDTH = "ImageMaxWidthpx";
        private const string FIELD_CONFIGKEY_IMAGEMAXHEIGHT = "ImageMaxHeightpx";

        private static int TryReadConfigValueAsInt(string keyName, int defaultValue)
        {
            int result = defaultValue;
            string rawValue = ConfigurationManager.AppSettings[keyName];
            if (!string.IsNullOrEmpty(rawValue))
            {
                if (!int.TryParse(rawValue, out result))
                    result = defaultValue;
            }
            return result;
        }

        private static string TryReadConfigValueAsString(string keyName, string defaultValue)
        {
            string result = defaultValue;
            string rawValue = ConfigurationManager.AppSettings[keyName];
            if (!string.IsNullOrEmpty(rawValue))
            {
                result = rawValue;
            }
            return result;
        }

        private static string OverrideSettingIfConfigIsValidDirectotry(string keyName, string defaultValue)
        {
            string result = TryReadConfigValueAsString(keyName, defaultValue);
            if (result != defaultValue)
            {
                if (!Directory.Exists(result))
                {
                    Trace.WriteLine(string.Format(
                                  "Switching {0} back to Directory  {1} as Directory {2} does not exist",
                                  keyName, defaultValue, result));
                    result = defaultValue;
                }
            }
            return result;
        }

        static void Main(string[] args)
        {
            // Attach the output window to the console to report of work done.
            Trace.Listeners.Add(
                new TextWriterTraceListener(System.Console.Out));
            
            // get default values 
            string startDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            // assume the source is the same as the exe to deal with a simple case of 
            // copy CA.Console.ResizeImage.exe into the directory and double click on it.
            string sourceImageDirectory = startDirectory;
            string resizedImageDirectory = Path.Combine(startDirectory, "ResizedImages");

            // Now we try get the read values from the config file if it exists  
            sourceImageDirectory = OverrideSettingIfConfigIsValidDirectotry(FIELD_CONFIGKEY_SOURCEIMAGE_DIR,
                                                                            sourceImageDirectory);
            resizedImageDirectory = OverrideSettingIfConfigIsValidDirectotry(FIELD_CONFIGKEY_RESIZEDIMAGE_DIR,
                                                                             resizedImageDirectory);
            int width = TryReadConfigValueAsInt(FIELD_CONFIGKEY_IMAGEMAXWIDTH, 500);
            int height = TryReadConfigValueAsInt(FIELD_CONFIGKEY_IMAGEMAXHEIGHT, 500);

            // Now look for override values specified via the command arguments 
            if (args != null)
            {
                foreach (string arg in args)
                {
                    if (arg.Length > 3)
                    {
                        switch ((arg.Substring(0, 3).ToLower()))
                        {
                            case "-s:":
                                {
                                    sourceImageDirectory = arg.Substring(3);
                                    break;
                                }
                            case "-d:":
                                {
                                    resizedImageDirectory = arg.Substring(3);
                                    break;
                                }
                            case "-w:":
                                {
                                    int.TryParse(arg.Substring(3), out width);
                                    break;
                                }
                            case "-h:":
                                {
                                    int.TryParse(arg.Substring(3), out height);
                                    break;
                                }
                        }
                    }
                }
            }

            ResizeImageLib lib = new ResizeImageLib(sourceImageDirectory, resizedImageDirectory, width, height);
            lib.ReSizeImages();
        }
    }
}

ResizeImageLib.cs

using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace CA.Console.ResizeImage
{
    public class ResizeImageLib
    {
        private const string FIELD_SUPPORTED_IMAGES = "jpg,jpeg,gif,bmp,png";        
        private string _sourceImageDirectory;
        private string _resizedImageDirectory;
        private Size _maxSize = new Size();
    
        public ResizeImageLib(string sourceImageDirectory, string resizedImageDirectory, int maxWidth, int maxHeight)
        {
            _sourceImageDirectory = sourceImageDirectory;
            if (_sourceImageDirectory.EndsWith(@"\"))
                _sourceImageDirectory.Substring(0, _sourceImageDirectory.Length - 1);
            if (!Directory.Exists(_sourceImageDirectory))
                throw new DirectoryNotFoundException(string.Format("Directory {0}Not Found.", _sourceImageDirectory));
            _resizedImageDirectory = resizedImageDirectory;
            if (_resizedImageDirectory.EndsWith("@\"))
                _resizedImageDirectory.Substring(0, _resizedImageDirectory.Length - 1);

            if (!Directory.Exists(_resizedImageDirectory))
                Directory.CreateDirectory(_resizedImageDirectory);
            if (_sourceImageDirectory == _resizedImageDirectory)
            {
                throw new NotSupportedException(
                    string.Format(
                    "The source and Resized Image Directory {0} cannot be the same. This avoids overwriting the orginal images ",
                        _sourceImageDirectory));
            }
            _maxSize.Width = maxWidth;
            _maxSize.Height = maxHeight;

            Trace.WriteLine(
                   string.Format("Stating to process all {2} files with target Max Width='{0}px' and Max Height = '{1}px'.",
                _maxSize.Width, _maxSize.Height, FIELD_SUPPORTED_IMAGES));
        }

        private Image ResizeImage(Image imgToResize, Size maxSize)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            // now do calc to work out aspect ratio 
            float nPercentW = ((float)maxSize.Width / (float)sourceWidth);
            float nPercentH = ((float)maxSize.Height / (float)sourceHeight);
            float nPercent = nPercentH < nPercentW ? nPercentH : nPercentW;
            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap iBitmap = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage(iBitmap);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic; // do the highest quality resize
            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();
            return iBitmap;
        }

        protected void ReSizeImages(string extentionToProcess)
        {
            ImageFormat saveFormat;
            switch (extentionToProcess.ToLower())
            {
                case "jpg":
                    saveFormat = ImageFormat.Jpeg;
                    break;
                case "jpeg":
                    saveFormat = ImageFormat.Jpeg;
                    break;
                case  "gif":
                    saveFormat = ImageFormat.Gif;
                    break;
                case "png":
                    saveFormat = ImageFormat.Png;
                    break;
                case "bmp":
                    saveFormat = ImageFormat.Bmp;
                    break;
                default:
                    saveFormat = ImageFormat.Jpeg;
                    break;
            }

            string[] sourceFiles = Directory.GetFiles(_sourceImageDirectory,
                                                                string.Format("*.{0}", extentionToProcess));
            foreach(string imageFile in sourceFiles)
            {
                string imageFileName = Path.GetFileName(imageFile);
                try
                {
                    Trace.WriteLine(string.Format("Processing {0}", imageFileName));
                    Image imgToResize = Image.FromFile(imageFile);
                    Image smallImage = ResizeImage(imgToResize, _maxSize);
                    string outputFileName = Path.Combine(_resizedImageDirectory, imageFileName);
                    if (File.Exists(outputFileName))
                    {
                        Trace.WriteLine(string.Format("Replacing output file {0}", outputFileName));
                        File.Delete(outputFileName);
                    }
                    smallImage.Save(outputFileName, saveFormat);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("Error Processing image {0} Error Message was {1}", imageFileName, ex.Message));

                }
            }
        }

         public void ReSizeImages()
         {
             string[] extentionToProcess = FIELD_SUPPORTED_IMAGES.Split(',');
             foreach (string extention in extentionToProcess)
             {
                 ReSizeImages(extention);
             }
         }
    }
}

If you have the .net Framework installed you can download the precompiled application CA.Console.ResizeImage.exe.zip (4.69 kb)

Tags: ,

.NET Development | DataTable

Comments are closed

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012 Code Associate