Created
January 29, 2015 06:55
-
-
Save xcud/a3bba62f75d2cfd145b9 to your computer and use it in GitHub Desktop.
Quickly determine whether a given path is an image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static bool IsImage(string path) | |
{ | |
Dictionary<string, string[]> knownImageHeaders = new Dictionary<string, string[]>() | |
{ | |
{"jpg", new [] { "FF", "D8" } }, | |
{"bmp", new [] { "42", "4D" } }, | |
{"gif", new [] { "47", "49", "46" } }, | |
{"tif", new [] { "49", "49", "2A" } }, | |
{"png", new [] { "89", "50", "4E", "47", "0D", "0A", "1A", "0A" } }, | |
}; | |
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) | |
{ | |
fs.Seek(0, SeekOrigin.Begin); | |
List<string> bytesIterated = new List<string>(); | |
for (int i = 0; i < 8; i++) | |
{ | |
bytesIterated.Add(fs.ReadByte().ToString("X2")); | |
bool isImage = knownImageHeaders.Values.Any(img => !img.Except(bytesIterated).Any()); | |
if (isImage) | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment