Build an Image Thumbnail Generator

Automatically generate thumbnail images of every JPEG in a directory.

Doug Seven

October 30, 2009

3 Min Read
ITPro Today logo

A Day in the Life of a Developer

LANGUAGE: C#

 

Build an Image Thumbnail Generator

Automatically generate thumbnail images of every JPEG ina directory.

 

By Doug Seven

 

In a recent project, my team was challenged to create aWeb page that generates thumbnail images of every JPEG image file in thedirectory that was not a thumbnail already. We accomplished this using classesin the System.Drawing and System.IO namespaces.

 

The goal was to create a Web Form that would generatethumbnails 72 pixels tall while maintaining their aspect ratio and save them tothe same directory, with the text "thumb_" at the beginning of the filename.All the code for this process is handled in the Page_Load event handler method.

 

Start by creating a variable for the file system path tothe images directory:

 

         String _path =Server.MapPath("images/");

  if (!_path.EndsWith(@"") )

    _path +=@"";

 

Using the System.IO.DirectoryInfoclass and an array of FileInfoobjects, create an array of files, which are the JPEG (*.jpg) files:

 

         DirectoryInfo _di= new DirectoryInfo(_path);

  FileInfo[] _fi =_di.GetFiles("*.jpg");

 

Next, eliminate any file that starts with the text"thumb_", then create a System.Drawing.Imageobject from the file:

 

         foreach (FileInfo _f in  _fi)

  {

    if (!_f.Name.StartsWith("thumb_") )

    {

      String _imgName =_f.Name;

      System.Drawing.Image_img =

         System.Drawing.Image.FromFile(_path + _imgName);

 

If the Image.Heightproperty is greater than 72 (in other words, the image is taller than 72pixels), resize the image. The important thing is to maintain the image'saspect ratio. To do this, determine the difference between the height and widthand use that value to determine the width of the thumbnail:

 

         if ( _img.Height> 72 )

      {

        Int32 _height =_img.Height;

        Int32 _width =_img.Width;

        Bitmap _imgOutput;

        Double _dif;

 

        _dif =Convert.ToDouble(Decimal.Divide(_width,_height));

        _width =Convert.ToInt32(Math.Ceiling(72 * _dif));

 

Now create a new Bitmap object from the Image object, passing in the newlydetermined width and the height of 72 pixels. Discard the original Image object, which releases a hold onthe image file:

 

        _imgOutput = newBitmap(_img, _width, 72);

        _img.Dispose();

 

Finally, save the new Bitmapobject as a JPEG file, using the ImageFormatenumeration:

 

         try

        {

          _imgOutput.Save(_path +

         "thumb_" +

_imgName.ToLower(),

System.Drawing.Imaging.ImageFormat.Jpeg);

 

          _imgOutput.Dispose();

          Response.Write("thumb_" +

         _imgName.ToLower() +

" Saved
");

        }

        catch ( Exception_ex )

        {

          Response.Write("Error SavingFile
");

          Response.Write(_ex.Message);

          Response.Write("
");

          Response.Write(_ex.StackTrace);

          Response.Write("
");

        }

      }

    }

  }

 

The code for the ThumbnailGenerator is offered in C#,along with five sample JPEG images.

 

The project referenced in this article is available fordownload.

 

As one of the co-founders of DotNetJunkies (http://www.dotnetjunkies.com), acontent-based online training resource for .NET developers, Doug Seven has beenbuilding applications with the .NET Framework since the summer of 2000. Sevenhas co-authored five books related to the .NET Framework: Programming Data-Driven Web Applications withASP.NET (Sams), ASP.NET: Tips, Tutorials& Code (Sams), Professional ADO.NET(Wrox), Developing Custom Controls for ASP.NET(Sams), and ASP.NET Security (Wrox).Seven's professional .NET consulting clients include Microsoft, theMassachusetts Institute of Technology (MIT) and Tricordia LLC, and the work hehas been involved in has included both C# and Visual Basic .NET, Webapplications, mobile device applications, XML Web Services, Windows Formsdevelopment, and console and service applications. E-mail Doug at [email protected].

 

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like