Skip to content

Instantly share code, notes, and snippets.

@xcud
Created January 29, 2015 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xcud/a3bba62f75d2cfd145b9 to your computer and use it in GitHub Desktop.
Save xcud/a3bba62f75d2cfd145b9 to your computer and use it in GitHub Desktop.
Quickly determine whether a given path is an image
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