28 February, 2012
4 Comments
1 category
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].
Tags: C#
Category: Uncategorized
Very nice article, so fast!
Thank you for sharing.
Best,
Karl
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
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
Just what I needed – thanks for sharing