Creating a Transparent PNG from a Scanned Image

One of the many parts of my sketchnoting process that I took from Mike Rohde's Sketchnote Handbook is scanning the finished sketch in black and white and adding colour to the image later.

Adding colour usually means using Photoshop or Paint.Net to separate the image into two (or sometimes more) layers. The top layer contains the inked drawing and the bottom layer will contain the colour, so that the finished image looks like the colour was applied first and the ink on top.

To make this work, the ink layer needs to have the white background made transparent. This is a painful, general purpose algorithm for a paint program to do - using a magic wand selection - but can be done more easily by a specific program. Coincidentally, like one what I wrote :)


using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace transpng
{
	class Program
	{
		static int Main(string[] args)
		{
			if (args.Length == 0)
			{
				System.Console.WriteLine("transpng <filename>");
				return 1;
			}

			string filename = args[0];

			if (!File.Exists(filename))
			{
				System.Console.WriteLine("File \'{0}\' does not exist", filename);
				return 1;
			}

			using (Image fromFile = Image.FromFile(filename))
			{
				using (Bitmap bitmap = new Bitmap(fromFile))
				{
					bitmap.MakeTransparent(Color.White);

					string newName = Path.Combine(Path.GetDirectoryName(filename), 
							Path.GetFileNameWithoutExtension(filename) + "_transparent" + Path.GetExtension(filename));

					if (File.Exists(newName))
						File.Delete(newName);

					bitmap.Save(newName, ImageFormat.Png);
				}
			}

			return 0;
		}
	}
}

This simple console app takes the name of an image file as an argument, changes the background colour to transparent and then saves it again with a new suffix so that the original file is left in tact.