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?
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.
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.
来源:https://stackoverflow.com/questions/2150504/how-can-i-check-the-color-depth-of-a-bitmap