November 27, 2003

Image Loading Goodness

Happy Thanksgiving!

I took a crack at two things this morning. First, I took some old C# code I wrote that traverses a directory structure and gets information on each file. Second, I use the System.Drawing library to get image information. Finally, I output all of the results.

The directory traversal turns out to be trivial. I implemented this as a simple recursive function as follows:

static int traverseFiles(FileAction action, DirectoryInfo dir)
{
     int numFiles = 0;
 
 FileInfo[] files = dir.GetFiles();
     foreach (FileInfo f in files) 
     {      
          if (action.doAction(f))
          {
               numFiles++;
           }
      }
 
 DirectoryInfo[] subdirs = dir.GetDirectories();
     foreach (DirectoryInfo d in subdirs) 
     {
          numFiles += traverseFiles(action, d);
      }
 
 return numFiles;
}

The FileAction argument is my simplistic shot at making the loop generic. My default implementation tries to load the file into a Bitmap() object. If this fails with a throw of System.ArgumentException, doAction() returns false. Here is the implementation of doAction().

public bool doAction(FileInfo file)
{
     ImageInfo image = new ImageInfo();
     try
     {
          image.Load(file.FullName);
          Console.WriteLine(file.FullName + " " + image.Width + "x" + image.Height);
          image.Unload();
          return true;
      }
     catch (System.ArgumentException)
     {
          return false;
      }
}

The ImageInfo class was lifted from AspHeute (AspToday, a German site I think). Thanks Christoph Wille. There is one error in their example, where the Width() wrapper returns the internal Bitmap() Height property.

The code for the sample I, uncreatively, named FindFiles.cs is available for your compiling pleasure.

Compiling can be done at the command prompt as follows:

csc FindFiles.cs
Posted by Nick Codignotto at November 27, 2003 08:50 AM
Posted to Programming
Comments
Post a comment









Remember personal info?






Valid XHTML 1.0!   Valid CSS!