/// <summary> /// 生成缩略图 /// </summary> /// <param name="image"></param> /// <param name="proportion"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public static Image CreateThumb(Image image, ThumbnailProportion proportion, int width, int height) { if (image == null) { throw new ArgumentNullException("图片为空image"); } int x = 0, y = 0, ow = image.Width, oh = image.Height, towidth = width, toheight = height; switch (proportion) { case ThumbnailProportion.WIDTH_HEIHT: break; case ThumbnailProportion.WIDTH: toheight = image.Height * width / image.Width; break; case ThumbnailProportion.HEIHT: towidth = image.Width * height / image.Height; break; case ThumbnailProportion.CUT: //剪切图片高比宽长 if ((double)image.Width / (double)image.Height > (double)towidth / (double)toheight) { oh = image.Height; ow = image.Height * towidth / toheight; y = 0; x = (image.Width - ow) / 2; } else { ow = image.Width; oh = image.Width * height / towidth; x = 0; y = (image.Height - oh) / 2; } break; } //指定位图大小 Bitmap bmp = new Bitmap(towidth, toheight); //创建画布 using (Graphics gs = Graphics.FromImage(bmp)) { gs.SmoothingMode = SmoothingMode.HighQuality; gs.CompositingQuality = CompositingQuality.HighQuality; gs.InterpolationMode = InterpolationMode.HighQualityBicubic; //清空画布并以透明背景色填充 gs.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 gs.DrawImage(image, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); return(bmp); } }
/// <summary> /// 剪裁图片 /// </summary> /// <param name="abPath"></param> /// <param name="cut"></param> /// <param name="resize"></param> /// <returns></returns> private Image CutImage(string abPath, string cut, string resize) { Image image = Image.FromFile(abPath); if (resize.StartsWith("w_") && resize.StartsWith("h_")) { return(image); } ThumbnailProportion pro = ThumbnailProportion.WIDTH; int width = 0, height = 0; string w, h; if (resize.IndexOf('x') > -1) { var arr = resize.Split("x"); for (int i = 0; i < arr.Length; i++) { if (arr[i].StartsWith("w_")) { w = arr[i].Replace("w_", ""); int.TryParse(w, out width); } else { h = arr[i].Replace("h_", ""); int.TryParse(h, out height); } } } else if (resize.StartsWith("h_")) { h = resize.Replace("h_", ""); int.TryParse(h, out height); } else if (resize.StartsWith("w_")) { w = resize.Replace("w_", ""); int.TryParse(w, out width); } switch (cut) { case "m_fill": pro = ThumbnailProportion.CUT; if (width <= 0 || height <= 0) { return(image); } break; case "m_fixed": pro = ThumbnailProportion.WIDTH_HEIHT; if (width <= 0 || height <= 0) { return(image); } break; case "m_h": pro = ThumbnailProportion.HEIHT; if (height <= 0) { return(image); } break; case "m_w": pro = ThumbnailProportion.WIDTH; if (width <= 0) { return(image); } break; default: return(image); } var thumb = ImageHelper.CreateThumb(image, pro, width, height); image.Dispose(); return(thumb); }