生成高质量缩略图

调用:

View Code
1 int width = 190;
2 int height = 190;
3 Bitmap source = new Bitmap("c:\\someimage.jpg");
4 System.Drawing.Image thumb = source.GetThumbnailImage(width,height,null,IntPtr.Zero);
5 thumb.Save("C:\\someimageshot.jpg");
6 thumb.Dispose();

 

函数:

View Code
 1 public static Bitmap CreateThumbnail(Bitmap source, int thumbWi, int thumbHi, bool maintainAspect)
 2         {
 3             if (source.Width < thumbWi && source.Height < thumbHi) return source;
 4             System.Drawing.Bitmap ret = null;
 5             try
 6             {
 7                 int wi, hi;
 8 
 9                 wi = thumbWi;
10                 hi = thumbHi;
11 
12                 if (maintainAspect)
13                 {
14                     if (source.Width > source.Height)
15                     {
16                         wi = thumbWi;
17                         hi = (int)(source.Height * ((decimal)thumbWi / source.Width));
18                     }
19                     else
20                     {
21                         hi = thumbHi;
22                         wi = (int)(source.Width * ((decimal)thumbHi / source.Height));
23                     }
24                 }
25                 ret = new Bitmap(wi, hi);
26                 using (Graphics g = Graphics.FromImage(ret))
27                 {
28                     g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
29                     g.FillRectangle(Brushes.White, 0, 0, wi, hi);
30                     g.DrawImage(source, 0, 0, wi, hi);
31                 }
32             }
33             catch
34             {
35                 ret = null;
36             }
37 
38             return ret;
39         }

另类用途:

比如某张云图特别大。要在首页上缩小显示。第一想法就是强制设定img的width和height。这个方法对ie8完美运行。但是ie7和6会出现图片压缩严重失真现象。这时就可以用大图转成缩略图来实现。读取大图的时候生成缩略图,并读取缩略图。下次再thumb.Save同一个缩略图文件。这样也不占用空间。

posted @ 2012-05-10 11:05  一篮饭特稀  阅读(254)  评论(0编辑  收藏  举报