When Images Met Mini-Me

Use GetThumbnailImage to generate thumbnails on the fly.

Hot Tip




When Images Met Mini-Me

Use GetThumbnailImage to generate thumbnails on the fly.


By Jeff Prosise


Ever fetched an image from a database for display in a Web page and wished the image were smaller so it would fit nicely into an HTML table cell? The .NET Framework Class Library's Image class offers a GetThumbnailImage method that makes resizing images on the fly a piece of cake. The following code sample uses ADO.NET to extract an image from the Employees table of SQL Server's Northwind database. Then it calls GetThumbnailImage on the Bitmap object encapsulating the image to shrink it to a height of 48 pixels while maintaining the image's aspect ratio:


SqlConnection connection = new SqlConnection


Bitmap bitmap = null;

Image image = null;


try {

    connection.Open ();

    SqlCommand cmd = new SqlCommand

         ("select photo from employees " +

         "where employeeid='1'", connection);

    byte[] blob = (byte[]) cmd.ExecuteScalar ();


    stream.Write (blob, 78, blob.Length - 78);

    bitmap = new Bitmap (stream);


    // Shrink the image, but maintain its aspect ratio

    int width = 48;

    int height = (int) (width *

         ((double) bitmap.Height / (double) bitmap.Width));

    image = bitmap.GetThumbnailImage

         (width, height, null, IntPtr.Zero);





finally {

    if (image != null)

        image.Dispose ();

    if (bitmap != null)

        bitmap.Dispose ();

     stream.Close ();

    connection.Close ();



For improved performance, cache the image once you've resized it, and satisfy subsequent requests for the same image by delivering the thumbnail straight from the cache. Caching allows you to avoid redundant database accesses and unnecessary calls to GetThumbnailImage, too. That's a win no matter you score it!


Jeff Prosise is author of several books, including Programming Microsoft .NET (Microsoft Press). He also is a co-founder of Wintellect (http://www.wintellect.com), a software consulting and education firm that specializes in .NET. Got a question for this column? Submit queries to [email protected].





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