4 Comments

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 Replies to “Fastest way to read dimensions from a picture / image file in C#”

  1. in your sample, in call – Image.FromStream(stream, false, false), be aware of 3rd parameter because if your app is webapp and is hosted in web hosting which does not allow “full trust” apps you could end with exception.
    More info:
    http://stackoverflow.com/a/420490/316886

  2. 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.

Related Posts