/** * 無損縮放圖片 * bitmap 需要縮放的圖片 * w 需要縮放的寬度 * h 需要縮放的高度 * */ public static System.Drawing.Bitmap TBScaleBitmap(System.Drawing.Bitmap bitmap, int w, int h, string mode) { System.Drawing.Bitmap map = new System.Drawing.Bitmap(w, h); System.Drawing.Graphics gra = System.Drawing.Graphics.FromImage(map); gra.Clear(System.Drawing.Color.Transparent);//清空畫布並以透明背景色填充 gra.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; //使繪圖質量最高,即消除鋸齒 gra.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; gra.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; gra.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; gra.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; int towidth = w; int toheight = h; int x = 0; int y = 0; int ow = bitmap.Width; int oh = bitmap.Height; switch (mode) { case "HW": //指定高寬縮放(可能變形) break; case "W": //指定寬,高按比例 toheight = bitmap.Height * w / bitmap.Width; break; case "H": //指定高,寬按比例 towidth = bitmap.Width * h / bitmap.Height; break; case "Cut": //指定高寬裁減(不變形) if ((double)bitmap.Width / (double)bitmap.Height > (double)towidth / (double)toheight) { oh = bitmap.Height; ow = bitmap.Height * towidth / toheight; y = 0; x = (bitmap.Width - ow) / 2; } else { ow = bitmap.Width; oh = bitmap.Width * h / towidth; x = 0; y = (bitmap.Height - oh) / 2; } break; case "MaxHW"://最大寬高比例縮放,比如原100*50->50*30,則結果是50*25 var rmaxhw_d1w = bitmap.Width * 1.0 / w; var rmaxhw_d2h = bitmap.Height * 1.0 / h; if (rmaxhw_d1w > rmaxhw_d2h) { if (rmaxhw_d1w <= 1) { towidth = bitmap.Width; h = bitmap.Height; goto case "HW"; } towidth = w; goto case "W"; } if (rmaxhw_d2h <= 1) { towidth = bitmap.Width; h = bitmap.Height; goto case "HW"; } toheight = h; goto case "H"; default: break; } gra.DrawImage(bitmap, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); gra.Flush(); gra.Dispose(); bitmap.Dispose(); return map; }