Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine if file is an image

Tags:

c#

file

image

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 any more elegant way of determining if a file is an image (any image type) without the hacky check like above?

like image 282
leora Avatar asked Mar 22 '09 04:03

leora


People also ask

How do I identify image files?

If you are having trouble and want to check if you photo is a JPEG, look at the writing under the photo in its file name. If it ends . jpg or . jpeg- then the file is a JPEG and will upload.

How can you tell if a file is a PNG?

Open a file in a Hex editor (or just a binary file viewer). PNG files start with 'PNG', . jpg files should have 'exif'or 'JFIF' somewhere in the beginning.


2 Answers

Check the file for a known header. (Info from link also mentioned in this answer)

The first eight bytes of a PNG file always contain the following (decimal) values: 137 80 78 71 13 10 26 10

like image 200
Mitch Wheat Avatar answered Sep 26 '22 10:09

Mitch Wheat


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         }     } } 
like image 25
bendewey Avatar answered Sep 23 '22 10:09

bendewey