tsJensen

A quest for software excellence...

Image MIME Type from the Byte[]

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.