8.8 Show a Thumbnail for an Image


Problem

You need to show thumbnails (small representations of a picture) for the images in a directory.

Solution

Read the image from the file using the static FromFile method of the System.Drawing.Image class. You can then retrieve a thumbnail using the Image.GetThumbnailImage method.

Discussion

The Image class provides the functionality for generating thumbnails through the GetThumbnailImage method. You simply need to pass the width and height of the thumbnail you want (in pixels), and the Image class will create a new Image object that fits these criteria. Antialiasing is used when reducing the image to ensure the best possible image quality, although some blurriness and loss of detail is inevitable. ( Antialiasing is the process of removing jagged edges, often in resized graphics, by adding shading with an intermediate color .) In addition, you can supply a notification callback, allowing you to create thumbnails asynchronously.

When generating a thumbnail, it's important to ensure that the aspect ratio remains constant. For example, if you reduce a 200 x 100 picture to a 50 x 50 thumbnail, the width will be compressed to one quarter and the height will be compressed to one half, distorting the image. To ensure that the aspect ratio remains constant, you can change either the width or the height to a fixed size , and then adjust the other dimension proportionately.

The following example reads a bitmap file and generates a thumbnail that is not greater than 50 x 50 pixels, while preserving the original aspect ratio.

 using System; using System.Drawing; using System.Windows.Forms; public class Thumbnails : System.Windows.Forms.Form {     // (Designer code omitted.)     Image thumbnail;     private void Thumbnails_Load(object sender, System.EventArgs e) {              Image img = Image.FromFile("test.jpg");         int thumbnailWidth = 0, thumbnailHeight = 0;         // Adjust the largest dimension to 50 pixels.         // This ensures that a thumbnail will not be larger than 50x50 pixels.         // If you are showing multiple thumbnails, you would reserve a 50x50         // pixel square for each one.         if (img.Width > img.Height) {                      thumbnailWidth = 50;             thumbnailHeight = Convert.ToInt32(((50F / img.Width) *               img.Height));         }else {                      thumbnailHeight = 50;             thumbnailWidth = Convert.ToInt32(((50F / img.Height) *               img.Width));         }         thumbnail = img.GetThumbnailImage(thumbnailWidth, thumbnailHeight,            null, IntPtr.Zero);     }     private void Thumbnails_Paint(object sender,       System.Windows.Forms.PaintEventArgs e) {              e.Graphics.DrawImage(thumbnail, 10, 10);     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net