Click here to Skip to main content
Click here to Skip to main content

Bitonal (TIFF) Image Converter for .NET

, 16 Feb 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
How to add bitonal image editing support to your applications
Sample Image - BitonalImageConverter.gif

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.

// Get an ImageCodecInfo object that represents the TIFF codec.
ImageCodecInfo imageCodecInfo = GetEncoderInfo("image/tiff");
System.Drawing.Imaging.Encoder encoder = 
       System.Drawing.Imaging.Encoder.Compression;
EncoderParameters encoderParameters = new EncoderParameters(1);

// Save the bitmap as a TIFF file with group IV compression.
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:

  1. Copy the image bytes for the original RGB image into a byte array.
  2. Create a new, bitonal image with the same dimensions as the source image.
  3. Create a byte array of the necessary size to contain the bits for the bitonal image.
  4. 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.
  5. 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.

License

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

Share

About the Author

Michael A. McCloskey
Web Developer
United States United States
I have been a "true blue" Microsoft developer since the earliest DOS days. I have coded in Turbo-C for DOS, VB 2->6, VB.NET, and C#. I enjoy graphics coding when I have the time, but tend to earn my living doing data layer and middle tier stuff. I love it all and only regret there's not enough time in the day to know everything about everything.
 
I am currently working as a software architect in Atlanta, Georgia and when I'm not coding, I'm pondering or reading anything that helps increase my understanding of the meaning of life and the nature of the universe, or at least my understanding of the .NET framework class library.

Comments and Discussions

 
QuestionYour article is not need Pinmember__Radik__28-Feb-14 5:34 
AnswerRe: Your article is not need PinmemberMichael A. McCloskey28-Feb-14 12:10 
GeneralRe: Your article is not need Pinmember__Radik__28-Feb-14 16:01 
GeneralMy vote of 5 PinmemberDelliturriG6-Feb-14 0:26 
GeneralMy vote of 5 Pinmembersapien4u11-Sep-13 5:57 
GeneralMy vote of 5 Pinmemberveggiemanuk5-Jun-12 9:23 
QuestionThis example not working PinmemberMember 302199712-Dec-11 22:11 
Questionconversion to base64 string PinmemberDaveeeeeeeeee1-Dec-11 2:19 
AnswerRe: conversion to base64 string PinmemberMichael A. McCloskey1-Dec-11 2:59 
GeneralRe: conversion to base64 string PinmemberDaveeeeeeeeee1-Dec-11 4:08 
GeneralRe: conversion to base64 string PinmemberMichael A. McCloskey1-Dec-11 13:44 
GeneralRe: conversion to base64 string Pinmemberafcm66620-Mar-13 4:47 
Questionusing TIFF with 2400 dpi? PinmemberMember 46061351-Nov-11 3:32 
AnswerRe: using TIFF with 2400 dpi? PinmemberMichael A. McCloskey1-Nov-11 5:57 
QuestionHelp! Pinmemberimran_akh18-Jul-11 2:15 
AnswerRe: Help! PinmemberMichael A. McCloskey18-Jul-11 3:22 
GeneralRe: Help! Pinmemberimran_akh18-Jul-11 6:06 
GeneralRe: Help! PinmemberMichael A. McCloskey18-Jul-11 7:35 
GeneralRe: Help! PinmemberImran Akhtar 9918-Jul-11 10:45 
GeneralRe: Help! PinmemberImran Akhtar 9918-Jul-11 10:57 
GeneralRe: Help! PinmemberImran Akhtar 9918-Jul-11 11:12 
GeneralRe: Help! PinmemberMichael A. McCloskey18-Jul-11 11:28 
QuestionHelp needed to convert the tiff images into bitonal PinmemberSrikanthRN4-Oct-11 12:05 
GeneralGreat Article... Thanks Pinmembermeeram3952-May-11 22:47 
GeneralRe: Great Article... Thanks PinmemberMichael A. McCloskey16-May-11 2:56 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.141022.2 | Last Updated 16 Feb 2010
Article Copyright 2006 by Michael A. McCloskey
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid