ASP.NET生成高质量缩略图通用函数

  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. Image originalImage = Image.FromFile(originalImagePath);   
  12. int towidth = width;   
  13. int toheight = height;   
  14. int x = 0;   
  15. int y = 0;   
  16. int ow = originalImage.Width;   
  17. int oh = originalImage.Height;   
  18. switch (mode)   
  19. {   
  20. case "HW":    //指定高宽缩放(可能变形)   
  21. break;   
  22. case "W":    //指定宽,高按比例   
  23. toheight = originalImage.Height * width/originalImage.Width;   
  24. break;   
  25. case "H":    //指定高,宽按比例   
  26. towidth = originalImage.Width * height/originalImage.Height;   
  27. break;   
  28. case "Cut":    //指定高宽裁减(不变形)   
  29. if((double)originalImage.Width/(double)originalImage.Height > (double)towidth/(double)toheight)   
  30. {   
  31. oh = originalImage.Height;   
  32. ow = originalImage.Height*towidth/toheight;   
  33. y = 0;   
  34. x = (originalImage.Width - ow)/2;   
  35. }   
  36. else  
  37. {   
  38. ow = originalImage.Width;   
  39. oh = originalImage.Width*height/towidth;   
  40. x = 0;   
  41. y = (originalImage.Height - oh)/2;   
  42. }   
  43. break;   
  44. default :   
  45. break;   
  46. }   
  47. //新建一个bmp图片   
  48. Image bitmap = new System.Drawing.Bitmap(towidth,toheight);   
  49. //新建一个画板   
  50. Graphics g = System.Drawing.Graphics.FromImage(bitmap);   
  51. //设置高质量插值法   
  52. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;   
  53. //设置高质量,低速度呈现平滑程度   
  54. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;   
  55. //清空画布并以透明背景色填充   
  56. g.Clear(Color.Transparent);   
  57. //在指定位置并且按指定大小绘制原图片的指定部分   
  58. g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),   
  59. new Rectangle(x, y, ow,oh),   
  60. GraphicsUnit.Pixel);   
  61. try  
  62. {   
  63. //以jpg格式保存缩略图   
  64. bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);   
  65. }   
  66. catch(System.Exception e)   
  67. {   
  68. throw e;   
  69. }   
  70. finally  
  71. {   
  72. originalImage.Dispose();   
  73. bitmap.Dispose();   
  74. g.Dispose();   
  75. }   
  76. }  

posted on 2008-10-02 22:18  nathally  阅读(118)  评论(0)    收藏  举报

导航