Click here to Skip to main content
15,881,715 members
Articles / Multimedia / GDI+

Bitonal (TIFF) Image Converter for .NET

Rate me:
Please Sign up or sign in to vote.
4.82/5 (45 votes)
16 Feb 2010CPOL5 min read 436.5K   7.5K   116   92
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):

C#
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:

C#
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.

C#
// 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)


Written By
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

 
QuestionHelp needed to convert the tiff images into bitonal Pin
SrikanthRN4-Oct-11 12:05
SrikanthRN4-Oct-11 12:05 
GeneralGreat Article... Thanks Pin
meeram3952-May-11 22:47
meeram3952-May-11 22:47 
GeneralRe: Great Article... Thanks Pin
Michael A. McCloskey16-May-11 2:56
Michael A. McCloskey16-May-11 2:56 
GeneralCreating a new bitonal bitmap from an existing... Pin
MightyZot11-Apr-11 9:46
MightyZot11-Apr-11 9:46 
GeneralVB.NET Version Pin
gotorg16-Mar-11 13:25
gotorg16-Mar-11 13:25 
GeneralMy vote of 5 Pin
Member 307909830-Nov-10 22:05
Member 307909830-Nov-10 22:05 
GeneralSaving the converted bitonal image Pin
Saransh Chintha25-Oct-10 9:33
Saransh Chintha25-Oct-10 9:33 
GeneralRe: Saving the converted bitonal image Pin
Michael A. McCloskey25-Oct-10 11:52
Michael A. McCloskey25-Oct-10 11:52 
I'm afraid I don't understand. The example code that comes with the project saves the result out to a CCITT Group IV Format. It's important to use the encoder parameters to trigger the codec to use the CCITT4 format.

The code is shown below:

      // Convert image to bitonal for saving to file<br />
            Bitmap bitonalBitmap = Converter.ConvertToBitonal(rgbBitmap);<br />
<br />
            // Display converted image<br />
            convertedImage.Image = bitonalBitmap;<br />
<br />
            // Get an ImageCodecInfo object that represents the TIFF codec.<br />
            ImageCodecInfo imageCodecInfo = GetEncoderInfo("image/tiff");<br />
            System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Compression;<br />
            EncoderParameters encoderParameters = new EncoderParameters(1);<br />
<br />
            // Save the bitmap as a TIFF file with group IV compression.<br />
            EncoderParameter encoderParameter = new EncoderParameter(encoder, (long)EncoderValue.CompressionCCITT4);<br />
            encoderParameters.Param[0] = encoderParameter;<br />
            bitonalBitmap.Save(@"..\..\Bitonal-Out.tif", imageCodecInfo, encoderParameters);

GeneralThanks! Pin
TomDratler30-Aug-10 18:16
TomDratler30-Aug-10 18:16 
GeneralRe: Thanks! Pin
Michael A. McCloskey1-Sep-10 2:58
Michael A. McCloskey1-Sep-10 2:58 
GeneralGood work Pin
msp.netdev10-May-10 11:03
msp.netdev10-May-10 11:03 
GeneralTurbo-C Pin
StevenHenning25-Feb-10 5:28
StevenHenning25-Feb-10 5:28 
Generalbyte order ! Pin
murx15-Feb-10 10:41
murx15-Feb-10 10:41 
GeneralRe: byte order ! Pin
Michael A. McCloskey15-Feb-10 14:05
Michael A. McCloskey15-Feb-10 14:05 
GeneralRe: byte order ! Pin
Michael A. McCloskey17-Feb-10 1:12
Michael A. McCloskey17-Feb-10 1:12 
Questionhow to get data from the tags of a TIFF image [modified] Pin
gilvani11-Aug-09 2:55
gilvani11-Aug-09 2:55 
AnswerRe: how to get data from the tags of a TIFF image Pin
Shayne P Boyer9-Mar-10 2:07
Shayne P Boyer9-Mar-10 2:07 
GeneralThank you! Pin
daelin24-Apr-09 4:47
daelin24-Apr-09 4:47 
GeneralRe: Thank you! Pin
Michael A. McCloskey24-Apr-09 11:14
Michael A. McCloskey24-Apr-09 11:14 
GeneralRe: Thank you! Pin
Member 26480075-May-09 23:54
Member 26480075-May-09 23:54 
GeneralBug with the converter Pin
chucklepie31-Mar-09 3:30
chucklepie31-Mar-09 3:30 
GeneralRe: Bug with the converter Pin
murx2-Feb-10 9:03
murx2-Feb-10 9:03 
GeneralRe: Bug with the converter Pin
Michael A. McCloskey15-Feb-10 14:12
Michael A. McCloskey15-Feb-10 14:12 
GeneralRe: Bug with the converter Pin
Michael A. McCloskey17-Feb-10 1:13
Michael A. McCloskey17-Feb-10 1:13 
Questiontiff image controlling using asp.net with C# coding Pin
Sumesh N24-Sep-08 19:01
Sumesh N24-Sep-08 19:01 

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.