1 /// <summary> 2 /// 生成缩略图 3 /// </summary> 4 /// <param name="originalImagePath">源图路径(物理路径)</param> 5 /// <param name="thumbnailPath">缩略图路径(物理路径)</param> 6 /// <param name="width">缩略图宽度</param> 7 /// <param name="height">缩略图高度</param> 8 /// <param name="mode">生成缩略图的方式</param> 9 public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode) 10 { 11 originalImagePath = string.Format(@"{0}{1}\{2}", StrHelp.GetPhysicalPath(),
ConfigurationManager.AppSettings["UploadPath"],
originalImagePath); 12 thumbnailPath = string.Format(@"{0}{1}\{2}", StrHelp.GetPhysicalPath(), ConfigurationManager.AppSettings["UploadPath"], thumbnailPath); 13 System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath); 14 15 int towidth = width; 16 int toheight = height; 17 18 int x = 0; 19 int y = 0; 20 int ow = originalImage.Width; 21 int oh = originalImage.Height; 22 23 switch (mode) 24 { 25 case "HW"://指定高宽缩放(可能变形) 26 break; 27 case "W"://指定宽,高按比例 28 if (originalImage.Width < width) 29 { 30 towidth = originalImage.Width; 31 toheight = originalImage.Height; 32 } 33 else 34 { 35 toheight = originalImage.Height * width / originalImage.Width; 36 } 37 break; 38 case "H"://指定高,宽按比例 39 if (originalImage.Height < height) 40 { 41 toheight = originalImage.Height; 42 towidth = originalImage.Width; 43 } 44 else 45 { 46 towidth = originalImage.Width * height / originalImage.Height; 47 } 48 break; 49 case "Cut"://指定高宽裁减(不变形) 50 if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) 51 { 52 oh = originalImage.Height; 53 ow = originalImage.Height * towidth / toheight; 54 y = 0; 55 x = (originalImage.Width - ow) / 2; 56 } 57 else 58 { 59 ow = originalImage.Width; 60 oh = originalImage.Width * height / towidth; 61 x = 0; 62 y = (originalImage.Height - oh) / 2; 63 } 64 break; 65 default: 66 break; 67 } 68 69 //新建一个bmp图片 70 System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); 71 72 //新建一个画板 73 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); 74 75 //设置高质量插值法 76 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; 77 78 //设置高质量,低速度呈现平滑程度 79 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 80 81 //清空画布并以透明背景色填充 82 g.Clear(System.Drawing.Color.Transparent); 83 84 //在指定位置并且按指定大小绘制原图片的指定部分 85 g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), 86 new System.Drawing.Rectangle(x, y, ow, oh), 87 System.Drawing.GraphicsUnit.Pixel); 88 89 try 90 { 91 string Path = thumbnailPath.Substring(0, thumbnailPath.LastIndexOf('\\')); 92 if (!Directory.Exists(Path)) 93 { 94 Directory.CreateDirectory(Path); 95 } 96 97 //以jpg格式保存缩略图 98 bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); 99 } 100 catch (System.Exception e) 101 { 102 throw e; 103 } 104 finally 105 { 106 originalImage.Dispose(); 107 bitmap.Dispose(); 108 g.Dispose(); 109 } 110 }