Introduction
The .NET framework provides rich support for generating and manipulating bitmap images, but it lacks one significant feature that is imperative for image processing -- the ability to modify and then save modified bitonal (i.e., black and white or one-bit per pixel) images. Bitonal images are commonly used in document management and document imaging applications for scanned documents. Bitonal images are most commonly stored in the TIFF (Tagged Image File Format) file format with a CCITT Group IV compression algorithm.
The Problem
The .NET Framework supports loading and displaying bitonal images, but that's where the support ends. All drawing in .NET requires a Graphics
object, but a Graphics
object cannot be created from a bitonal image. Go ahead and try it now if you don't believe me. I'll wait...
Here's some code that demonstrates the issue (assuming Bitonal-In.tif is a bitonal image):
Bitmap originalBitmap = new Bitmap(@"Bitonal-In.tif");
Graphics g2 = Graphics.FromImage(originalBitmap);
This code will generate an "A Graphics object cannot be created from an image that has an indexed pixel format." exception, thereby thwarting our desire to modify our bitonal image. I know, I couldn't believe it either.
The Solution (Almost)
We can work around the previous exception by converting the bitonal image into an RGB (Red/Green/Blue) bitmap for modification. The Converter
class included with this article contains a static
method, ConvertToRGB
, for doing so. The code for this method is as follows:
public static Bitmap ConvertToRGB(Bitmap original)
{
Bitmap newImage = new Bitmap(original.Width, original.Height,
PixelFormat.Format32bppArgb);
newImage.SetResolution(original.HorizontalResolution,
original.VerticalResolution);
Graphics g = Graphics.FromImage(newImage);
g.DrawImageUnscaled(original, 0, 0);
g.Dispose();
return newImage;
}
This gives us a bitmap we can use to create a Graphics
object and modify the image, so all is well with the world once again. Well... almost, but not quite.
A New, But Different Problem
We can now happily modify and display our image all day long (albeit with the larger memory footprint of a 32 bit per pixel RGB image), but we are thwarted once again if we wish to save our modified image back to disk in a bitonal format. The following code will generate a "Parameter is not valid." exception when attempting to save our 32 bit RGB image back to a bitonal format.
ImageCodecInfo imageCodecInfo = GetEncoderInfo("image/tiff");
System.Drawing.Imaging.Encoder encoder =
System.Drawing.Imaging.Encoder.Compression;
EncoderParameters encoderParameters = new EncoderParameters(1);
EncoderParameter encoderParameter = new EncoderParameter(encoder,
(long)EncoderValue.CompressionCCITT4);
encoderParameters.Param[0] = encoderParameter;
bitonalBitmap.Save(@"Bitonal-Out.tif", imageCodecInfo, encoderParameters);
The problem arises as a result of the .NET framework's inability to encode an RGB image into a bitonal file format. It is the primary intent of this article to address this issue.
The Solution (I Really Mean It This Time)
While the .NET framework does indeed support saving bitonal images, it provides no means for converting an RGB image into a bitonal image, which is the crux of the problem. We can't use the same method used to go from bitonal to RGB because we can't create a new bitonal image and get a Graphics
object to draw on it. We must resort to something completely different -- direct image byte manipulation (Aaahh!!! Did he just say that !??).
While it is beyond the scope of this article to dig into the memory structure of bitmaps, I will mention briefly the task at hand. 32-bit RGB bitmaps use four bytes of memory for each pixel (picture element) in the bitmap. One byte each is used for the Red-ness, Green-ness, and Blue-ness of the pixel, and one byte is used to represent the Alpha (or transparency) of the pixel. The RGB value of 255-255-255 represents white, and a value of 0-0-0 represents black. Bitonal images, on the other hand, use a single bit to represent each pixel in the image, and eight pixels are packed into each byte of memory used to represent the image.
The BitmapData
class in .NET provides a LockBits
method, which gives us direct access to the image bytes for a bitmap. We can use this method to retrieve the image bytes for an existing image into a byte[]
, modify the image bytes, and then write the image bytes back to the bitmap, thus modifying the bitmap. To convert an RGB bitmap into a bitonal bitmap, we proceed as follows:
- Copy the image bytes for the original RGB image into a byte array.
- Create a new, bitonal image with the same dimensions as the source image.
- Create a
byte
array of the necessary size to contain the bits for the bitonal image.
- Walk the pixels in the source data, and set the appropriate bit in the destination data if the sum of the red, green, and blue values exceeds a certain threshold.
- Copy the destination byte array back to the new bitonal bitmap.
Comments
While searching for a solution to this problem, I came across other snippets to do this type of conversion, but they all suffered from the same problem: They were S....L....O....W..... The method provided with this article performs the conversion of a typical 300 DPI (Dot Per Inch) image on my machine (a 3 gigahertz P4) in about 100 milliseconds. While a lot of C# imaging applications resort to pointer arithmetic and unsafe
code blocks, the code in this article is hereby deemed Completely Safe and does not need to resort to such medieval methods.
Room For Improvement
The RGB to bitonal conversion method provided with this article performs a threshold type conversion of the image in which a destination pixel is either black or white depending on the brightness of the pixel in the source image. One beneficial improvement to the code would be the addition of half-toning or dithering algorithms to produce a higher quality output from color images. The method provided with this article was written for use in document imaging applications in which the source image is already a bitonal image, so this was not a necessity for my purposes, but I see how it could prove useful if this code was to be used to produce bitonal images from color images with a wider variety of source colors.
Sample Project
The sample project included with this project is a Windows Forms application that utilizes the Converter
class to convert an existing bitonal image to RGB, draw some text on it, then save it back to disk in bitonal format. The project contains the minimal amount of code necessary to demonstrate the technique.