tags:

views:

374

answers:

4

I am looping through a directory and copying all files. Right now I am doing string.EndsWith checks for ".jpg" or ".png", etc . .

Is there a more elegant way of determining if a file is an image (any image type) without the hacky check above?

+12  A: 

Check the file for a known header.

[Update: moving info out of comment]. The first eight bytes of a PNG file always contain the following (decimal) values: 137 80 78 71 13 10 26 10

Mitch Wheat
The first eight bytes of a PNG file always contain the following (decimal) values: 137 80 78 71 13 10 26 10. BTW, it was a quick google!
Mitch Wheat
Wow, Clarion is still around! That's a surprise - I cut one or two teeth on Clarion back in about '95.
ProfK
+2  A: 

Check out System.IO.Path.GetExtension

Here is a quick sample.

public static readonly List<string> ImageExtensions = new List<string> { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG" };

private void button_Click(object sender, RoutedEventArgs e)
{
    var folder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    var files = Directory.GetFiles(folder);
    foreach(var f in files)
    {
        if (ImageExtensions.Contains(Path.GetExtension(f).ToUpperInvariant()))
        {
            // process image
        }
    }
}
bendewey
erm, that's what the poster is saying he wants to do more than....
Mitch Wheat
He said he is checking to see if the string.EndsWith from what I gathered
bendewey
yeah, but it's still a string comparison. What if I rename a .jpf file to be .txt?
Mitch Wheat
There are two possible interepretations of the question; either 'EndsWith' is hacky (in which case this answer is what the OP wants), or 'using the filename' is hacky, in which case @MitchWheat's answer is what the OP wants. I prefer Mitch's, but upvoted both.
Brian
If you use the extension, be sure to convert it to lowercase before you do your comparisons. (Many digital cameras, for example, produce .JPG files.)
Thomas
@Brian... well said.
harpo
+2  A: 

See if this helps.

EDIT: Also, Image.FromFile(....).RawFormat might help. It could throw an exception if the file is not an image.

shahkalpesh
+1  A: 

Not exactly the answer you need. But if it’s the Internet then MIME type.

Cherian