Resizing Images and Coder's Laziness

28.10.2009 • 21:32 • permalinkComments (0)

I have long had the feeling that I would enjoy being a photographer, a theory which I've now been validating since around mid summer. Borrowing a decent camera from my parents I've been running around town and the surrounding countryside trying to take some great pictures.

Obviously it's no fun just looking at your pictures all by your lonesome so I had to upload them to the web. Flickr seemed a natural choice and I've been uploading the most interesting photos from each set. Now if you go look at them you might notice a pattern in the size of the images, namely that the maximum dimension of each picture is 1200 pixels. This is just a measure to keep the file size down but it is something of a bother to do and while it's not a huge issue it did prompt my Coder's Laziness. Coder's Laziness is what I call that useful feeling a good programmer will get when he is faced with a repetitive task that leads him to code up an app or script to do it for him. And that is what I did.

I find the ability to just sit down and create a tool that will bend the computer to my will and solve some problem I have to be one of the greatest rewards of being a programmer. Taking the case of the resizing app I needed, I ended up with a working solution after about 30 minutes work - it even had a few bonus features such as a progress bar and settings for compression quality for the Jpg encoding. In fact, the C# code is so small and simple I provide it to you in its entirety:

  1. public partial class ResizeForm : Form
  2. {
  3.    public ResizeForm()
  4.    {
  5.       InitializeComponent();
  6.    }
  7.  
  8.    private void resizeButton_Click(object sender, EventArgs e)
  9.    {
  10.       progressBar.Value = 0;
  11.  
  12.       string url = urlBox.Text;
  13.       int maxDimension = int.Parse(dimensionBox.Text);
  14.       int quality = (int)qualityScale.Value;
  15.  
  16.       var dir = new DirectoryInfo(url);
  17.       if (!dir.Exists)
  18.       {
  19.          MessageBox.Show("No such directory exists!");
  20.          return;
  21.       }
  22.  
  23.       var resizedDir = new DirectoryInfo(Path.Combine(url, "resized/"));
  24.       if (!resizedDir.Exists) resizedDir.Create();
  25.  
  26.       var jpegs = dir.GetFiles().Where(file => file.Extension == ".jpg").ToList();
  27.  
  28.       int current = 0;
  29.       foreach (var imageFile in jpegs)
  30.       {
  31.          var original = new Bitmap(imageFile.FullName);
  32.          Image resized = ResizeImage(original, maxDimension);
  33.          string savename = resizedDir.FullName + imageFile.Name;
  34.          SaveJpg(resized, savename, quality);
  35.          current++;
  36.          progressBar.Value = (int)(current / (float)jpegs.Count) * 100;
  37.       }
  38.    }
  39.  
  40.    private static Image ResizeImage(Image originalBitmap, int maxDimension)
  41.    {
  42.       float aspectX = maxDimension / (float)originalBitmap.Width;
  43.       float aspectY = maxDimension / (float)originalBitmap.Height;
  44.       float actualAspect = Math.Min(aspectX, aspectY);
  45.  
  46.       int sourceWidth = (int)(originalBitmap.Width * actualAspect);
  47.       int sourceHeight = (int)(originalBitmap.Height * actualAspect);
  48.  
  49.       var resized = new Bitmap(sourceWidth, sourceHeight);
  50.  
  51.       Graphics g = Graphics.FromImage(resized);
  52.       g.DrawImage(originalBitmap, new Rectangle(0, 0, resized.Width, resized.Height));
  53.       return resized;
  54.    }
  55.  
  56.    private static ImageCodecInfo GetEncoderInfo(String mimeType)
  57.    {
  58.       return ImageCodecInfo.GetImageEncoders().FirstOrDefault(codecInfo => codecInfo.MimeType == mimeType);
  59.    }
  60.  
  61.    private void SaveJpg(Image image, string fileName, long quality)
  62.    {
  63.       EncoderParameters parameters = new EncoderParameters(1);
  64.       parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
  65.       ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");
  66.       image.Save(fileName, codecInfo, parameters);
  67.    }

If you want to look at the GUI or just play around with the code you can download the project and do with it what you want. Enjoy.

Update: The project has been replaced with a newer version.

Comments

Name:

Comment (no HTML):