Skip navigation

Build an Image Thumbnail Generator

Automatically generate thumbnail images of every JPEG in a directory.

A Day in the Life of a Developer

LANGUAGE: C#

 

Build an Image Thumbnail Generator

Automatically generate thumbnail images of every JPEG in a directory.

 

By Doug Seven

 

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

 

The goal was to create a Web Form that would generate thumbnails 72 pixels tall while maintaining their aspect ratio and save them to the 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 to the images directory:

 

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

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

    _path += @"\";

 

Using the System.IO.DirectoryInfo class and an array of FileInfo objects, 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.Image object 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.Height property is greater than 72 (in other words, the image is taller than 72 pixels), resize the image. The important thing is to maintain the image's aspect ratio. To do this, determine the difference between the height and width and 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 newly determined width and the height of 72 pixels. Discard the original Image object, which releases a hold on the image file:

 

        _imgOutput = new Bitmap(_img, _width, 72);

        _img.Dispose();

 

Finally, save the new Bitmap object as a JPEG file, using the ImageFormat enumeration:

 

         try

        {

          _imgOutput.Save(_path +

         "thumb_" +

_imgName.ToLower(),

System.Drawing.Imaging.ImageFormat.Jpeg);

 

          _imgOutput.Dispose();

          Response.Write("thumb_" +

         _imgName.ToLower() +

" Saved</b><br>");

        }

        catch ( Exception _ex )

        {

          Response.Write("<b>Error Saving File</b><br>");

          Response.Write(_ex.Message);

          Response.Write("<br>");

          Response.Write(_ex.StackTrace);

          Response.Write("<br>");

        }

      }

    }

  }

 

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

 

The project referenced in this article is available for download.

 

As one of the co-founders of DotNetJunkies (http://www.dotnetjunkies.com), a content-based online training resource for .NET developers, Doug Seven has been building applications with the .NET Framework since the summer of 2000. Seven has co-authored five books related to the .NET Framework: Programming Data-Driven Web Applications with ASP.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, the Massachusetts Institute of Technology (MIT) and Tricordia LLC, and the work he has been involved in has included both C# and Visual Basic .NET, Web applications, mobile device applications, XML Web Services, Windows Forms development, and console and service applications. E-mail Doug at [email protected].

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish