A little puzzle came up today. Fetch an image out of a database and stream it down to the browser. The trick: we don't know what type of image is stored in the database. So I borrowed a little from our Python friends and this is what I ended up with.
internal static class ImageTypeFinder{ internal static string GetMimeType(byte[] image) { string retval = "image/jpeg"; string imgtype = GetImageType(image); switch (imgtype) { case "bmp": retval = "image/bmp"; break; case "gif": retval = "image/gif"; break; case "tif": retval = "image/tiff"; break; case "png": retval = "image/png"; break; } return retval; } internal static string GetImageType(byte[] image) { int len = image.Length; if (len > 32) len = 32; string first32 = ASCIIEncoding.ASCII.GetString(image, 0, len); return GetImageType(first32); } internal static string GetImageType(string first32) { string retval = string.Empty; if (first32.StartsWith("GIF87a") || first32.StartsWith("GIF89a")) retval = "gif"; else if (first32.StartsWith("MM") || first32.StartsWith("II")) retval = "tif"; else if (first32.Substring(6, 4) == "JFIF" || first32.Substring(6, 4) == "Exif") retval = "jpg"; else if (first32.StartsWith("BM")) retval = "bmp"; else if (first32.Substring(1, 3) == "PNG") retval = "png"; return retval; }}
It's a bit of an esoteric puzzle, but if you're trying to solve this one, the above code should help.
Page rendered at Tuesday, February 07, 2012 5:16:37 AM (Mountain Standard Time, UTC-07:00)
DisclaimerThe opinions expressed herein are just that, opinions. Don't have a fit if you think they're wrong. Post your comment or write your own blog.