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