2

With all the smarts of actually loading images being done by the .net framework, seems like I shouldn't have to repeat it all in my code by checking for magic numbers, or using a hack like this:

Private Function IsImage(FileName as String) As Boolean
    Try
        Using img As New Bitmap(FileName)
        End Using
    Catch ex as System.ArgumentException
        Return False
    End Try
    Return True
End Function

Am I missing something obvious, like System.Drawing.IsImage(stream)?

FastAl
  • 6,194
  • 2
  • 36
  • 60
  • possible duplicate of [determine if file is an image](http://stackoverflow.com/questions/670546/determine-if-file-is-an-image) – jgauffin Apr 20 '11 at 14:49
  • As to why doesn't the framework do it check out this post about how all features start at -100 points and people have to prove their need in comparison to other features. http://blogs.msdn.com/b/ericgu/archive/2004/01/12/57985.aspx – Chris Haas Apr 20 '11 at 14:52
  • I don't think that's particularly a 'hack'. It's using all the framework's smarts, which would be tricky to entirely replicate. – AakashM Apr 20 '11 at 15:13
  • @jgauffin - thanks for the comment - but in the quote from the answer for that post, 'Check the file for a known header' - That's what I meant by 'magic' numbers. I didn't want to have to code and test something new (the answer's link didn't have a mature/tested .net sample). – FastAl Apr 25 '11 at 14:13
  • @Chris Haas - Can you maybe just post an answer saying 'no"? I will probably continue to use my 'hack', I don't care about the type. thanks. – FastAl Apr 25 '11 at 14:16
  • @FastAl: They are not "magic" numbers. They are the headers specified in the standards. It's the only solid way to be sure if a file is an image or not. – jgauffin Apr 26 '11 at 04:55

1 Answers1

1

You will need to open up the file and read the relevant headers for the file types you want to support, as mentioned here:

determine if file is an image

I don't think there is anything already in the .NET framework that can do this for you, other than loading it into an image and querying the image format:

Find image format using Bitmap object in C#

An alternative theory (no actual facts to back this one up): perhaps the file in Windows holds meta-data that flags it as an image - in the same manner than the properties dialog seems to show artist information for audio files. This could be a cute way to avoid opening the file.

Edit by FastAl Jun 2020. More useful links:

Using .NET, how can you find the mime type of a file based on the file signature not the extension

Not what I asked for, but here are the magic #s:

https://en.wikipedia.org/wiki/List_of_file_signatures

https://www.garykessler.net/library/file_sigs.html

Community
  • 1
  • 1
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187