I needed a method to get the mime type of a System.Drawing Image instance that I'd loaded from an upload. All articles I was able to find online suggest some kind of lookup table solution. There's actually another way. Given an Image i, you can map from the i.RawFormat.Guid property to an ImageCodecInfo.FormatID. So it becomes a very simple for loop to get the MIME type of an image or bitmap. This works for any format System.Drawing/GDI+ supports (bmp, png, tiff, jpg/jpeg, etc). Here's the code:

public static stringGetMimeType(Imagei)
foreach (ImageCodecInfo codec inImageCodecInfo.GetImageDecoders())
if (codec.FormatID == i.RawFormat.Guid)
return codec.MimeType;

return "image/unknown";

This won't work for images that were created on the fly (will return "image/unknown"), but will work for all images that were loaded from some source (file, stream, byte[], etc).

My friend Rob Garrett recently started a Design Patterns post series on his blog. This seems like a great way to share experience with the community and stimulate thought and discussion. I decided to start a series on imaging with .NET, to share some of my experiences and the techniques that enable advanced solutions with .NET imaging and GDI+. This is the kickoff post for the series.

In my experience, simple things in .NET are well documented, but it can be hard to find information on how to do complex things. One thing that took me awhile to figure out is how to save a bitmap as a CCITT group 4 TIFF. It actually ends up being a simple process.

First, you need a monochrome (1bpp) source GDI+ Bitmap. .NET doesn't have a very good built in mechanism for converting from color to monochrome. The only reliable and performant method is a scale-to-grey algorithm written in unsafe code. That will be a topic for another post. For now, lets assume the GDI+ Bitmap is monochrome.

To set up for the save process, you need two things -- an EncoderParameters object set for CCITT G4, and an ImageCodecInfo that points to the GDI+ TIFF encoder.

First, the EncoderParameters object:

// Encoder parameters for CCITT G4
EncoderParameters eps = new EncoderParameters(1);

eps.Param[0] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionCCITT4);

Then, the ImageCodecInfo:

ImageCodecInfo[] ie = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo tiffEncoder = null;

for (int i = 0; i < ie.Length; i++)
if (ie[i].MimeType == "image/tiff")
tiffEncoder = ie[i];


If you want to set the image resolution to a standard resolution like 300x300 before you save, call the SetResolution method:

bmp.SetResolution(300, 300);

Once you have those two objects, given a 1bpp Bitmap bmp, it's a simple one method call to the Save method:

bmp.Save(fileName, tiffEncoder, eps);

If the Bitmap has multiple frames, this method will only save a single frame. I'll write another article in future on multiple frame images.