1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
/// <summary> /// 生成缩略图 /// </summary> /// <param name="imgPath">源图片路径</param> /// <param name="thumbnailPath">缩略图保存路径</param> /// <param name="newWidth">新宽度</param> /// <param name="newHeight">新高度</param> /// <param name="addSpace">是否添加空白</param> /// <returns></returns> public static void Thumbnail(string imgPath, string thumbnailPath, int newWidth, int newHeight, bool addSpace) { int sW, sH; // 按比例缩放 var imgSource = Image.FromFile(imgPath); var sWidth = imgSource.Width; var sHeight = imgSource.Height; if (sHeight > newHeight || sWidth > newWidth) { if ((sWidth * newHeight) > (sHeight * newWidth)) { sW = newWidth; sH = (newWidth * sHeight) / sWidth; } else { sH = newHeight; sW = (sWidth * newHeight) / sHeight; } } else { sW = sWidth; sH = sHeight; } var outBmp = addSpace ? new Bitmap(newWidth, newHeight) : new Bitmap(sW, sH); var x = 0; var y = 0; if (addSpace) { var whRate = newWidth > newHeight ? true : false; //宽是否大于高(新尺寸) x = whRate ? (newWidth - sW) / 2 : x; y = whRate ? (newHeight - sH) / 2 : y; } var g = Graphics.FromImage(outBmp); // 设置画布的描绘质量 g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgSource, new Rectangle(x, y, sW, sH), new Rectangle(0, 0, imgSource.Width, imgSource.Height), GraphicsUnit.Pixel); g.Dispose(); try { //保存图片 outBmp.Save(thumbnailPath, ImageFormat.Jpeg); } finally { imgSource.Dispose(); g.Dispose(); outBmp.Dispose(); } } |