C# 图像居中缩放(自动裁剪保证图像不被压扁或变长)

时间:2021-12-05 15:23:39
/// <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);
        }
    }