Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created April 11, 2014 07:43
Show Gist options
  • Select an option

  • Save AlexArchive/10447471 to your computer and use it in GitHub Desktop.

Select an option

Save AlexArchive/10447471 to your computer and use it in GitHub Desktop.
public static class ContentTypeIdentifier
{
public static ContentType IdentifyType(Stream contentStream)
{
byte[] contentHeader = new byte[4];
contentStream.Read(contentHeader, 0, 4);
return ResolveContentTypeBasedOnHeader(contentHeader);
}
private static ContentType ResolveContentTypeBasedOnHeader(byte[] header)
{
var jpg = new byte[] { 255, 216, 255, 224 };
var jpg2 = new byte[] { 255, 216, 255, 225 };
var png = new byte[] { 137, 80, 78, 71 };
var bmp = new byte[] { 66, 77 };
var gif = new byte[] { 71, 73, 70 };
if (jpg.SequenceEqual(header.Take(jpg.Length)))
return ContentType.Jpg;
if (jpg2.SequenceEqual(header.Take(jpg2.Length)))
return ContentType.Jpg;
if (png.SequenceEqual(header.Take(png.Length)))
return ContentType.Png;
if (bmp.SequenceEqual(header.Take(bmp.Length)))
return ContentType.Bmp;
if (gif.SequenceEqual(header.Take(gif.Length)))
return ContentType.Gif;
return ContentType.NotImage;
}
}
public enum ContentType
{
Jpg,
Png,
Bmp,
Gif,
NotImage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment