Click here to Skip to main content
15,881,882 members
Articles / Web Development / HTML

Acme Photo Resizer is a C# Program for Resizing Images in Bulk

Rate me:
Please Sign up or sign in to vote.
4.83/5 (5 votes)
20 Jan 2016CPOL4 min read 12.1K   557   5   1
In this article I will show how simple programs can help improve your photography work flow. Acme Photo resizer resizes JPG images in bulk. It can also add a copyright notice and the photograph's file name to each image. It was written to help me resize race photographs so that I could post them to

Image 1

Introduction

Acme Photo Resizer is a simple image processing program designed to resize programs in a bulk operation.

Background

As a way to support the local running community, I take photographs of local races where there is no official photographer. I post them to race web sites and Facebook. When you are posting hundreds of images, you need to reduce the file size to a size that is appropriate for the web-site. Facebook has gotten much better of late, and will display images 2048px wide. What I needed was an easy way to resize hundreds of images at once. While I don't charge for my race photographs, I do like to put a copyright notive and filename on each photograph. That was my motivation for writing this program.

I'm indebted to Code Project contributor Lev Danielyan for his EXIF metadata extraction library. I use the EXIF orientation tag to rotate images shot in portrait mode.

Image 2

Photograph resized to 600px wide.

Choosing Images

Acme Photo Resizer has a very basic interface. You specify your resize option, enter an optional Copyright Holder name, choose a set of JPG files and click the process button. The program shows a progress bar and lists the files processed in a list box. It places the resized images into a subfolder named "Resized" in the folder containing the selected JPG files.

The "Orientation" tag in the EXIF tag is used to determine the orientation of the photograph. The rotation is to ensure the photograph is resized with the correct orientation.

Performance and multi-threading

As I was writing this article, it occurred to me that I could improve performamce using multi-threading. Because the program iterates through a set of files, it was fairly straight forward to convert it to use the Parallel class’s ForEach method.

C#
Task t = Task.Factory.StartNew(() =>
{
   if (Parallel.ForEach(_Files, f =>
   {
      if (f.EndsWith(".jpg")) {
         ResizeImageFile(f, dir, perCent, pixelWidth, pixelHeight, copyrightHolder, flipHorizontal, flipVertical);
         ReportProgress(f);
      }
   }).IsCompleted) {
      Complete();
   }
});

The tricky part is updating controls in a multi-threaded environment. Controls can only be accessed on the thread that created them. Attempting to access them directly from inside a thread raises an exception. I had a method that updated a progress bar and a list box and I wanted to keep those features. I came across this code project article by Pablo Grisafi and it provided an elegant solution, so I adopted his technique. I appended the following extension method class to the form code file.

C#
static class FormExtensions
{
    static public void UIThread(this Form form, MethodInvoker code)
    {
        if (form.InvokeRequired)
        {
            form.Invoke(code);
            return;
        }
        code.Invoke();
    }
}

That enabled me to implement ReportProgress quite simply.

C#
private void ReportProgress(string f)
{
   this.UIThread(delegate
   {
      proBar.Increment(1);
      lstResized.Items.Add(f);
   });
}

I also needed a way to clean up once all the threads had completeted. I used the same technique.

C#
private void Complete()
{
   this.UIThread(delegate
   {
      //
      // Ensure progres bar is completed
      proBar.Value = proBar.Maximum;
      //
      // Reset cursor and re-enable form.
      Cursor.Current = Cursors.Default;
      this.Enabled = true;
   });
}

Resizing an Image

The method that does the resizing uses standard .Net libraries.

C#
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;

It is rather large. I built it using various examples I found on the web. I always say "Google is my manual".

C#
private static Image ScaleImage(Image imgPhoto, int? perCent, int? pixelWidth, int? pixelHeight, int orientation, ref Rectangle dest)
{
   int sourceWidth = imgPhoto.Width;
   int sourceHeight = imgPhoto.Height;
   int sourceX = 0;
   int sourceY = 0;
   int destWidth = 0;
   int destHeight = 0;
   int destX = 0;
   int destY = 0;
   //
   // Calculate the width and height of the resized photo
   // depending on which option was chosen.
   if (perCent != null) {
      if (perCent == 100) {
         return imgPhoto;
      }
      double nPercent = ((double)perCent / 100);
      destWidth = (int)(sourceWidth * nPercent);
      destHeight = (int)(sourceHeight * nPercent);
   }
   else if (pixelWidth != null) {
      if (sourceWidth == (int)(pixelWidth)) {
         return imgPhoto;
      }
      destWidth = (int)(pixelWidth);
      destHeight = (int)((destWidth * sourceHeight) / sourceWidth);
   }
   else {
      if (sourceHeight == (int)(pixelHeight)) {
         return imgPhoto;
      }
      destHeight = (int)pixelHeight;
      destWidth = (int)((destHeight * sourceWidth) / sourceHeight);
   }
   //
   // Create a bitmap for the resized photo
   Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
   bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
   //
   // Create a graphics object from the bitmap and set attributes for highest quality
   Graphics grPhoto = Graphics.FromImage(bmPhoto);
   grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
   grPhoto.SmoothingMode = SmoothingMode.HighQuality;
   grPhoto.CompositingQuality = CompositingQuality.HighQuality;
   grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
   //
   // Draw the new image
   grPhoto.DrawImage(imgPhoto,
                     new Rectangle(destX, destY, destWidth, destHeight),
                     new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                     GraphicsUnit.Pixel);
   //
   // Reorient, if necessary
   if (orientation == 8) {
      bmPhoto.RotateFlip(RotateFlipType.Rotate270FlipNone);
   }
   else if (orientation == 6) {
      bmPhoto.RotateFlip(RotateFlipType.Rotate90FlipNone);
   }
   //
   // return the Bit map and save its dimensions
   dest.Width = bmPhoto.Width;
   dest.Height = bmPhoto.Height;
   grPhoto.Dispose();
   return bmPhoto;
}

Flipping Images

Sometimes you end up with images that are flipped horizontally or vertically. In my case, it was old slides and negatives that I photographed from the wrong side. My usual processing program, DxO Optics Pro, does not have a flip funcion, so I added the capability to Acme Photo Resizer. Flipping only takes one line of code. x.RotateFlip(RotateFlipType.RotateNoneFlipX);

Saving Images

The Microsoft Documentation says "GDI+ uses image encoders to convert the images stored in Bitmap objects to various file formats. Image encoders are built into GDI+ for the BMP, JPEG, GIF, TIFF, and PNG formats. An encoder is invoked when you call the Save or SaveAdd method of a Image object." I used the following methods to save files using the JPEG encoder.

C#
private void SaveJpeg(string path, Bitmap img, long quality)
{
   // Encoder parameter for image quality
   EncoderParameter qualityParam =
       new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
   // Jpeg image codec
   ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
   if (jpegCodec == null)
      return;
   EncoderParameters encoderParams = new EncoderParameters(1);
   encoderParams.Param[0] = qualityParam;
   img.Save(path, jpegCodec, encoderParams);
}
private ImageCodecInfo GetEncoderInfo(string mimeType)
{
   // Get image codecs for all image formats
   ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
   // Find the correct image codec
   for (int i = 0; i < codecs.Length; i++) {
      if (codecs[i].MimeType == mimeType) {
         return codecs[i];
      }
   }
   return null;
}

I pass 90L to the quality parameter. That seems to give good quality and convenient file sizes.

Writing a Copyright notice

Writing to an image involves a few steps. This is the code I use.

C#
//
// Get graphics object from bitmap
Graphics g = Graphics.FromImage(y);
g.SmoothingMode = SmoothingMode.AntiAlias;
//
// Figure out fontsize relative to image width
int fontSize = (int)(_FontSize * 350.0 / x.HorizontalResolution);
//
// Specify font. Currently hard-coded.
Font font = new Font("Lucida Handwriting", fontSize, FontStyle.Bold);
int picNameWidth = (int)g.MeasureString(picName, font).Width;
//
// Write out notice and picture name in black, then white offset by 2 pixels
g.DrawString(copyrightNotice, font, Brushes.Black, new Point(10, dest.Height - 50));
g.DrawString(copyrightNotice, font, Brushes.White, new Point(12, dest.Height - 48));
g.DrawString(picName, font, Brushes.Black, new Point(dest.Width - 10 - picNameWidth, dest.Height - 50));
g.DrawString(picName, font, Brushes.White, new Point(dest.Width - 8 - picNameWidth, dest.Height - 48));
g.Dispose();

I write the text in black and white to give a slight shadow effect. This means it will still be readable if the background is very light or very dark.

Help

I created a help file in HTML. The Help file is displayed when the Help button is clicked.

Using the code

This code uses intermediate C# coding techniques. It could serve as a starting point for applications that need to resize images. It also illustrates how to get EXIF data and how to rotate photographs to the correct orientation.

It is multi-threaded and is able to update a progress bar and list box without cross threading issues, thanks to Pablo Grisafi.

As a photographer, I found this program made it much easier to upload large image galleries to sites like Facebook" .

Points of Interest

Acme Photo Resizer illustrates how to resize, rotate, flip and save images. It uses the Parallel class to improve performance on computers with multicore processors.

History

First Version for Code-Project

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Retired/Contractor
United States United States
I have been a software developer since 1969. I started writing Fortran programs for an IBM 1620 computer. That was followed by a few years writing commercial software for IBM 360/370 computers using PL/1. In 1979, my firm bought an Hewlett=Packard 3000 minicomputer. I developed a 4GL for this computer to make it easier to support pension fund applications.

In the 1990s, I moved to the US and worked as a consultant developing commercial applications using Visual Basic and various databases. I was the architect and lead developer for BETS, a VB6/Oracle application that administered healthcare benefits for Kaiser Permanente in Ohio. I later joined Kaiser Permanente and continued working on BETS.

When Microsoft stopped supporting VB6, the decision was made to convert BETS to a web based platform. Once again, I was the architect and lead developer, although we were fortunate to have a great web developer on the team. We converted 1.5 million lines of VB6 code to C# and javaScript. That project was very successful and Kaiser implemented BETS in four other regions. That was my last project before retiring.

I write games and personal applications for fun. Redback is the first project I've shared on Code Project. I have a checkers program written in C# and a web-based word program written in javaScript and jQuery in the works plus a couple of little image utilities that support my photography hobby.

Comments and Discussions

 
QuestionMultithreading update Pin
Pat Dooley31-Jan-17 1:03
professionalPat Dooley31-Jan-17 1:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.