生成缩率图项目实例
/// <summary> /// 生成缩略图 /// </summary> /// <param name="fileName">源图路径(绝对路径)</param> /// <param name="newFileName">缩略图路径(绝对路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">"HW":指定高宽缩放(不变形)</param> public static void MakeThumbnailImage(string fileName, string newFileName, int width, int height, string mode) { Image originalImage = Image.FromFile(fileName); int Imgwidth = width; int Imgheight = height; int towidth = width; int toheight = height; int tox = 0; int toy = 0; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case "HW"://等高宽缩放(不变形) if ((double)ow / (double)oh > (double)towidth / (double)toheight) { towidth = width; toheight = Convert.ToInt32((double)oh * (double)towidth / (double)ow); toy = (height - toheight) / 2; Imgwidth = width; Imgheight = height; } else { toheight = height; towidth = Convert.ToInt32((double)ow * (double)toheight / (double)oh); tox = (width - towidth) / 2; } break; case "W"://指定宽,高按比例 towidth = originalImage.Width > width ? width : originalImage.Width; toheight = originalImage.Height * towidth / originalImage.Width; Imgwidth = towidth; Imgheight = toheight; break; case "H"://指定高,宽按比例 toheight = originalImage.Height > height ? height : originalImage.Height; towidth = originalImage.Width * toheight / originalImage.Height; Imgwidth = towidth; Imgheight = toheight; break; case "Cut"://指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } Imgwidth = width; Imgheight = height; break; default: break; } //新建一个bmp图片 Bitmap b = new Bitmap(Imgwidth, Imgheight); try { //新建一个画板 Graphics g = Graphics.FromImage(b); //设置高质量插值法 g.InterpolationMode = InterpolationMode.HighQualityBicubic; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.CompositingQuality = CompositingQuality.HighQuality; //清空画布并以透明背景色填充 g.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new Rectangle(tox, toy, towidth, toheight), new Rectangle(0, 0, ow, oh), GraphicsUnit.Pixel); SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower())); g.Dispose(); } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); b.Dispose(); } }