C# 影象居中縮放(自動裁剪保證影象不被壓扁或變長)
阿新 • • 發佈:2019-01-30
/// <summary>
/// 居中縮放影象
/// </summary>
/// <param name="src">源</param>
/// <param name="dest">目標</param>
public static void ImageScale(Bitmap src, Bitmap dest)
{
if (src == null || dest == null)
throw new ArgumentNullException();
double srcScale;
double destScale;
srcScale = (double )src.Width / src.Height;
destScale = (double)dest.Width / dest.Height;
//計算長寬比
using (Graphics g = Graphics.FromImage(dest))
{
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
if (srcScale - destScale >= 0 && srcScale - destScale <= 0.001 )
{
//長寬比相同
g.DrawImage(src, new Rectangle(0, 0, dest.Width, dest.Height), new Rectangle(0, 0, src.Width, src.Height), GraphicsUnit.Pixel);
}
else if (srcScale < destScale)
{
//源長寬比小於目標長寬比,源的高度大於目標的高度
double newHeight;
newHeight = (double )dest.Height * src.Width / dest.Width;
g.DrawImage(src, new Rectangle(0, 0, dest.Width, dest.Height), new Rectangle(0, (int)((src.Height - newHeight) / 2), src.Width, (int)newHeight), GraphicsUnit.Pixel);
}
else
{
//源長寬比大於目標長寬比,源的寬度大於目標的寬度
double newWidth;
newWidth = (double)dest.Width * src.Height / dest.Height;
g.DrawImage(src, new Rectangle(0, 0, dest.Width, dest.Height), new Rectangle((int)((src.Width - newWidth) / 2), 0, (int)newWidth, src.Height), GraphicsUnit.Pixel);
}
}