determine if file is an image

Viewed 116862

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?

13 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

Check out System.IO.Path.GetExtension

Here is a quick sample.

public static readonly List<string> ImageExtensions = new List<string> { ".JPG", ".JPEG", ".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
        }
    }
}

See if this helps.

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

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

This is a tricky one. If file is not an Image an exception will thrown. From that we can check the file is image or not.

        using (Stream stream = File.OpenRead(file))
           {
               try
               {
                   using (Image sourceImage = Image.FromStream(stream, false, false))
                   {

                   }
               }
               catch (Exception x)
               {
                   if (x.Message.Contains("not valid"))
                   {
                     Console.Write("This is not a Image.");
                   }

               }
           }

This is what I use - it is just a tweak of @dylmcc's answer to make it a bit more readable.

public static bool IsRecognisedImageFile(string fileName)
{
    string targetExtension = System.IO.Path.GetExtension(fileName);
    if (String.IsNullOrEmpty(targetExtension))
    {
        return false;
    }

    var recognisedImageExtensions = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().SelectMany(codec => codec.FilenameExtension.ToLowerInvariant().Split(';'));

    targetExtension = "*" + targetExtension.ToLowerInvariant();
    return recognisedImageExtensions.Contains(targetExtension);
}

My simple code

public static List<string> GetAllPhotosExtensions()
    {
        var list = new List<string>();
        list.Add(".jpg");
        list.Add(".png");
        list.Add(".bmp");
        list.Add(".gif");
        list.Add(".jpeg");
        list.Add(".tiff");
        return list;
    }

Check if image file

public static bool IsPhoto(string fileName)
    {
        var list = FileListExtensions.GetAllPhotosExtensions();
        var filename= fileName.ToLower();
        bool isThere = false;
        foreach(var item in list)
        {
            if (filename.EndsWith(item))
            {
                isThere = true;
                break;
            }
        }
        return isThere;     
    }
Related