在下述程式代码中,函数MakeThumbImage(string sPath, string stPath, int nWidth, int nHeight, string sMode)创建上传文件的缩略图。其中,参数sPath表示源图路径、参数stPath表示缩略图的路径、参数nWidth表示缩略图的宽度、参数nHeight表示缩略图的高度、参数sMode表示生成缩略图的方式。
该函数在创建缩略图之前,首先获取源图,并构建源图的Image类的实例sImage,然后根据参数sMode,即创建缩图的模式,计算出缩图的高度和宽度。该函数处理了4种模式:
HW:指定图片的高度和宽度进行缩放;
H:指定图片的高度进行缩放;
W:指定图片的宽度进行缩放;
Cut:按照图片的原始比例,对图片对行缩放。
该函数在创建缩略图之前,首先获取源图,并构建源图的Image类的实例sImage,然后根据参数sMode,即创建缩图的模式,计算出缩图的高度和宽度。该函数处理了4种模式:
HW:指定图片的高度和宽度进行缩放;
H:指定图片的高度进行缩放;
W:指定图片的宽度进行缩放;
Cut:按照图片的原始比例,对图片对行缩放。
- /// <summary>
- /// 生成缩图
- /// </summary>
- /// <param name="sPath">源图路径</param>
- /// <param name="stPath">缩略图的路径</param>
- /// <param name="nWidth">缩略图的宽度</param>
- /// <param name="nHeight">缩略图的高度</param>
- /// <param name="sMode">生成缩略图的方式(HW:指定图片的高度和宽度进行缩放; H:指定图片的高度进行缩放; W:指定图片的宽图进行缩放; Cut:按照图片的源始比例,对图片对行缩放)</param>
- private void MakeThumbImage(string sPath, string stPath, int nWidth, int nHeight, string sMode)
- {
- System.Drawing.Image sImage = System.Drawing.Image.FromFile(sPath);
- int tw = nWidth;
- int th = nHeight;
- // 原始图片的宽度和高度
- int sw = sImage.Width;
- int sh = sImage.Height;
- int x = 0, y = 0;
- switch (sMode)
- {
- case "HW": // 指定高宽缩放
- break;
- case "W": // 指定图片的宽度,计算图片的高度
- th = sImage.Height * nWidth / sImage.Width;
- break;
- case "H": // 指明定图片的高度, 计算图片的宽度
- sw = sImage.Width * nHeight / sImage.Height;
- break;
- case "Cut": // 计算略图的大小
- if ((double)tw / (double)th < (double)nWidth / (double)nHeight)
- {
- sw = sImage.Width;
- sh = sImage.Width * nHeight / tw;
- x = 0;
- y = (sImage.Height - sh) / 2;
- }
- else
- {
- sh = sImage.Height;
- sw = sImage.Height * tw / th;
- y = 0;
- x = (sImage.Width - sw) / 2;
- }
- break;
- default:
- break;
- }
- // 创建bmp图片
- System.Drawing.Image bitmap = new System.Drawing.Bitmap(tw, th);
- // 创建Graphics对象g
- System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
- // 设置高质量插值法
- g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
- // 设置高质量,低速度呈现平滑程度
- g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
- // 清空画布并以透明背景色填充
- g.Clear(System.Drawing.Color.Transparent);
- // 在指定位置并且按指定大小绘制原图片的指定部份
- g.DrawImage(sImage, new System.Drawing.Rectangle(0, 0, tw, th), new System.Drawing.Rectangle(x, y, sw, sh), System.Drawing.GraphicsUnit.Pixel);
- try
- {
- // 采用jpg格式保存缩略图
- bitmap.Save(stPath, System.Drawing.Imaging.ImageFormat.Jpeg);
- }
- catch (Exception ex)
- {
- Response.Write(ex.Message);
- }
- finally
- {
- // 释放资源
- sImage.Dispose();
- bitmap.Dispose();
- g.Dispose();
- }
- }