Monday, June 9, 2014

C# Resize Image / Fit Image

After spending a good 10 minutes trying to find a program that can batch resize images from the command line by someone that looks trustworthy (enough to install on a shared server), I gave up and decided to write my own.

Here is the code in case it helps anyone.  This is C# and it compiles for .NET 2.0.  You'll need to add The assembly reference System.Drawing to your project.
ResizeImage.exe <filename> <maxWidth> <maxHeight> 
For example, calling "ResizeImage.exe hello.jpg 100 100" will decrease the width of hello.jpg to be 100 pixel or less and the height to be 100 pixels or less, maintaining its aspect ratio.  If hello.jpg is already smaller than 100x100, there will be no change.

You can batch resize many images by using a batch file.  For example, this will resize all images in a specified directory, including all subdirectories:
@FOR /F "delims=" %%A IN ('dir %1 /s /b') DO @"ResizeImage.exe" "%%A" %2 %3

For example, "BatchResize.bat c:\images 100 100" will resize all images in c:\images\...


using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

using System.IO;


namespace ResizeImage
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Please use arguments: ResizeImage myfile.jpg 640 480");
                return;
            }
            string fileName = args[0];
            int width = int.Parse(args[1]);
            int height = int.Parse(args[2]);
            if( width <= 0 || height <= 0 )
            {
                Console.WriteLine("Invalid width ("+width+") or height ("+height+")");
                return;
            }
            try
            {
                System.IO.FileStream fs = new FileStream(fileName, FileMode.Open);
                Image originalImage = Image.FromStream(fs);
                fs.Close();
                Image resizedImage = ResizeImage(originalImage, width, height);
                if (resizedImage != null)
                {
                    originalImage = null;
                    resizedImage.Save(fileName);
                    Console.WriteLine("Converted: " + fileName);
                }
            }
            catch( System.IO.FileNotFoundException )
            {
                Console.WriteLine("File not found: " + fileName);
            }
            catch (System.Exception e)
            {
                Console.WriteLine("Exception: " + e.ToString());
            }
        }

        static Image ResizeImage(Image image, int maxWidth, int maxHeight)
        {
            // Get the image's original width and height
            int originalWidth = image.Width;
            int originalHeight = image.Height;

            // To preserve the aspect ratio
            float ratioX = (float)maxWidth / (float)originalWidth;
            float ratioY = (float)maxHeight / (float)originalHeight;
            float ratio = Math.Min(ratioX, ratioY);

            // New width and height based on aspect ratio
            int newWidth = (int)(originalWidth * ratio);
            int newHeight = (int)(originalHeight * ratio);
            if (newWidth >= originalWidth || newHeight >= originalHeight)
                return null;

            return (Image)(new Bitmap(image, new Size(newWidth, newHeight)));
        }
    }
}

3 comments:

  1. Play cool gambling and win every day. top online casino games and slots Do not be afraid to win because you were born to win..

    ReplyDelete
  2. I love your creativity. Are you also searching for nursing writing services? we are the best solution for you. We are best known for delivering nursing writing services to students without having to break the bank.

    ReplyDelete