The fastest way to read the dimensions (width and height) from a picture / image file in C#, that I know of is:

DateTime startDateTime = DateTime.Now;
string sourceFolder = @"C:\Temp";

// Get all files from sourcefolder, including subfolders.
string[] sourceFiles = Directory.GetFiles(sourceFolder, "*", SearchOption.AllDirectories);
foreach (string file in sourceFiles)
{
    using (Stream stream = File.OpenRead(file))
    {
        using (Image sourceImage = Image.FromStream(stream, false, false))
        {
            Console.WriteLine(sourceImage.Width);
            Console.WriteLine(sourceImage.Height);
        }
    }
}
DateTime endDateTime = DateTime.Now;

Console.WriteLine(string.Format(
    "Total duration [{0}] seconds. Total image count [{1}].", 
    (endDateTime - startDateTime).TotalSeconds, 
    sourceFiles.Length));

Total duration [0,1855235] seconds. Total image count [33].

 

This is like 250x faster, then:

DateTime startDateTime = DateTime.Now;
string sourceFolder = @"C:\Temp";

// Get all files from sourcefolder, including subfolders.
string[] sourceFiles = Directory.GetFiles(sourceFolder, "*", SearchOption.AllDirectories);
foreach (string file in sourceFiles)
{
    using (Image sourceImage = Image.FromFile(file))
    {
        Console.WriteLine(sourceImage.Width);
        Console.WriteLine(sourceImage.Height);
    }
}
DateTime endDateTime = DateTime.Now;
Console.WriteLine(string.Format(
    "Total duration [{0}] seconds. Total image count [{1}].", 
    (endDateTime - startDateTime).TotalSeconds, 
    sourceFiles.Length));

Total duration [47,4575263] seconds. Total image count [33].

4 Comments

  1. I have been writing a C# application to build the image pages for my daughter Ann’s web page. I am trying to get each image to scale down properly. I thought about getting the image width and height. I found your site on Google.

    Error 1 The type or namespace name ‘Image’ could not be found (are you missing a using directive or an assembly reference?)

    Error 2 The name ‘Image’ does not exist in the current context

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.