views:

151

answers:

1

I am developing a document database application that handles TIFF images. When annotating images, in order for the user-interface to present only black and white as choices for bitonal (Format1bppIndexed) images versus multiple colors for images with a higher color depth I need to test for whether or not a TIFF is bitonal. Here is my function:

private bool IsBitonal(string filePath)
{
    bool isBitonal = false;
    try
    {
        Bitmap bitmap = new Bitmap(sourceFilePath);
        Graphics graphics = Graphics.FromImage(bitmap);
    }
    catch (Exception ex)
    {
        isBitonal = true;
    }
    return isBitonal;
}

It works but it is not graceful. The indexed pixel format exception that is thrown is described here: http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage.aspx.

Trapping an exception for normal program flow is poor practice. Also, it is conceivable that a different exception could be thrown. Is there a better way to implement an IsBitonal function that does not rely on trapping an exception?

I tried searching the web for information and I found examples of how to load a TIFF image and avoid the exception by converting to a different format but I couldn't find any examples of a simple test for whether or not a TIFF image is bitonal.

Thanks.

+3  A: 

Can you just check the PixelFormat Property of your bitmap?

private bool IsBitonal(string sourceFilePath)
{
    Bitmap bitmap = new Bitmap(sourceFilePath);
    return (bitmap.PixelFormat == PixelFormat.Format1bppIndexed)   
}

If that doesn't work, You should be able to look at the PropertyItems Collection in the Bitmap class and directly read the TIFF tags from the image.

See the TIFF spec here: http://www.awaresystems.be/imaging/tiff/tifftags/baseline.html

You could also look at the dimensions and Resolution of the image and contrast it with the filesize to get and idea of how many bits per pixel there are. (This probably wouldn't be very exact given compression and Metadata in the image).

Nate Heinrich
Checking the bitmap.PixelFormat property works. Thanks for the info.