views:

515

answers:

3

I'm working on an application that prints a folder of image files, including JPEG and TIFF. The TIFF images are usually Black and White (1bpp).

After loading the image, I want to determine if the image is Color or B&W or Grayscale so I can send the image to the right printer (color printer or black and white printer).

I'm using the Bitmap constructor image = new Bitmap(filename); to load the image.

EDIT: The answer to check the pixel depth is great for B&W. Any ideas on checking if the image is grayscale without iterating through every pixel?

+1  A: 

Just check this property

image.PixelFormat

It will match one of the values in System.Drawing.Imaging.PixelFormat

Though you would want to send more than just Black & White to the B&W printer, you should also send any gray scales there as well.

Neil N
Crazy, I dug through the list of members for the Bitmap class, not sure how I missed it.
Chris Thompson
I haven't accepted the answer yet because I was testing it. I did think about how to check grayscale too. Perhaps I should edit the question to clarify that.
Chris Thompson
A: 

Use its PixelFormat property.

Neil
A: 

The proper way to check this is:

For JPEG files you should check the appropriate properties using the PropertyItems collection of the Bitmap. This may contain the appropriate EXIF tags to help determine the bit depth. The next step would be to parse the JPEG header and look for the 'start of frame' marker and then the number of components in the image.

The final method is to load the JPEG into a Bitmap object and compare the number of pixels with the forumla (width * height * bytes_per_pixel). So if you load the bitmap and number of bytes of actual raw data is equal to (width * height) then you know it's a safe bet that the image has 1 byte per pixel and as such is grayscale.

The last thing you'll want to check is the PixelFormat of the bitmap itself.

For the TIFF file format you should do the same thing using the PropertyItems collection and check the appropriate tag mentioned in the spec. If these fail then do the image byte comparison and finally use the PixelFormat property as a last resort.