Manipulating Images with .NET


The completed project code for this article is available here:

The Problem

In building this website, I realized I needed to automate some of the image manipulation I perform on my travel photographs to get them published faster. This includes creating thumbnail pictures of different sizes to help web pages load faster and to add watermarks to the images if needed.

I have dealt with manipulating images before in .NET, so this seemed like an easy task, but one worth doing and writing about because the results are useful and practical. I wanted a program that I can point at a directory of images to generate thumbnails with watermarks. For the time being, I am OK running this program manually from time to time, so I will keep the structure simple.

System.Drawing.Graphics usage in ResizeImage method.

The Structure

I structured it as a Console application. All of the logic is contained in the Program.cs file. A few notes about the code regions:

  • 'Fields' contain the constants related to thumbnail image size (in pixels) and the watermark image file path.
  • 'Constructors' contain the Main entry point to the application and the core processing logic.
  • 'Methods' contain operations for resizing the image and adding the watermark.

The Code

The application simply takes a given folder path that contains photo albums, iterates through the image files in each photo album directory creating 4 thumbnail images for each photo. Portrait/landscape image ratios are accounted for and a folder is created for each thumbnail size - small, medium, large, etc. In the code, watermarks are added only to the large images.

Core loop in the program.


The coolest bits in the code probably revolve around how the image ratios are enforced and the actual use of the System.Drawing.Graphics class to draw the thumbnail images and watermarks. I used Expression Design to generate the watermarks.

A simple operation to add a watermark.

Simple code, but it saves me lots of time and helps me publish photo albums much sooner.

Tagged: #code

Posted on Jul 20, 2017