asp.net生成高清晰缩略图

来源:互联网 发布:淘宝手机端尺寸大小 编辑:程序博客网 时间:2024/04/30 08:38
  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.         public  void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height) 
  9.         { 
  10.           System.Drawing.Image   originalImage = System.Drawing.Image.FromFile(originalImagePath); 
  11.            int towidth = 0; 
  12.            int toheight =0; 
  13.             if(originalImage.Width>width &&originalImage.Height<height) 
  14.             { 
  15.                 towidth = width; 
  16.                 toheight = originalImage.Height; 
  17.             } 
  18.             if (originalImage.Width<width && originalImage.Height >height) 
  19.             { 
  20.                 towidth = originalImage.Width; 
  21.                 toheight = height; 
  22.             } 
  23.             if (originalImage.Width > width && originalImage.Height > height) 
  24.             { 
  25.                 towidth = width; 
  26.                 toheight = height; 
  27.             } 
  28.             if (originalImage.Width < width && originalImage.Height < height) 
  29.             { 
  30.                 towidth = originalImage.Width; 
  31.                 toheight = originalImage.Height; 
  32.             } 
  33.             int x = 0;//左上角的x坐标 
  34.             int y = 0;//左上角的y坐标 
  35.             
  36.             //新建一个bmp图片 
  37.          System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); 
  38.             //新建一个画板 
  39.             Graphics g = System.Drawing.Graphics.FromImage(bitmap); 
  40.             //设置高质量插值法 
  41.             g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; 
  42.             //设置高质量,低速度呈现平滑程度 
  43.             g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 
  44.             //清空画布并以透明背景色填充 
  45.             g.Clear(Color.Transparent); 
  46.             //在指定位置并且按指定大小绘制原图片的指定部分 
  47.             g.DrawImage(originalImage,x,y,towidth,toheight); 
  48.             try 
  49.             { 
  50.                 //以jpg格式保存缩略图 
  51.                 bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); 
  52.             } 
  53.             catch (System.Exception e) 
  54.             { 
  55.                 throw e; 
  56.             } 
  57.             finally 
  58.             { 
  59.                 originalImage.Dispose(); 
  60.                 bitmap.Dispose(); 
  61.                 g.Dispose(); 
  62.             } 
  63.         }

文章来源:wangjun8868的专栏

原创粉丝点击