Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a file an image?

Tags:

c#

image

In C# what is the best way to tell if a particular file is an image?

like image 347
jon37 Avatar asked Mar 24 '09 18:03

jon37


2 Answers

Most picture formats specify the file type in the first few bytes of the image. You can read in a few bytes and look for the correct headers.

File extensions technically don't hold any important data about the image. It just helps the OS figure out what program to use to open it. (But, checking the extn is probably the easiest way, and usually correct.)

like image 171
jjnguy Avatar answered Sep 30 '22 02:09

jjnguy


This isn't tested, but it's something like this:

private string MimeType (string Filename)
{
    string mime = "[default]";
    string ext = GetExtension(Filename).ToLower();
    Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (rk != null && rk.GetValue("Content Type") != null)
        mime = rk.GetValue("Content Type").ToString();
    return mime;
}

(Sorry, it's been awhile since I've done registry stuff)

like image 22
Matt Grande Avatar answered Sep 30 '22 03:09

Matt Grande