等比例缩放图片(C#)

       在使用图片的过程中,我们有时候需要将图片缩放到特定的宽度和高度,但是又不希望图片被直接拉伸而变形,而是实现图片的等比例缩放。类似于Winform的PictureBox的SizeMode属性的Zoom,而不是StretchImage。

 

  1.  
    //等比例缩放图片
  2.  
    private Bitmap ZoomImage(Bitmap bitmap, int destHeight, int destWidth)
  3.  
    {
  4.  
    try
  5.  
    {
  6.  
    System.Drawing.Image sourImage = bitmap;
  7.  
    int width = 0, height = 0;
  8.  
    //按比例缩放
  9.  
    int sourWidth = sourImage.Width;
  10.  
    int sourHeight = sourImage.Height;
  11.  
    if (sourHeight > destHeight || sourWidth > destWidth)
  12.  
    {
  13.  
    if ((sourWidth * destHeight) > (sourHeight * destWidth))
  14.  
    {
  15.  
    width = destWidth;
  16.  
    height = (destWidth * sourHeight) / sourWidth;
  17.  
    }
  18.  
    else
  19.  
    {
  20.  
    height = destHeight;
  21.  
    width = (sourWidth * destHeight) / sourHeight;
  22.  
    }
  23.  
    }
  24.  
    else
  25.  
    {
  26.  
    width = sourWidth;
  27.  
    height = sourHeight;
  28.  
    }
  29.  
    Bitmap destBitmap = new Bitmap(destWidth, destHeight);
  30.  
    Graphics g = Graphics.FromImage(destBitmap);
  31.  
    g.Clear(Color.Transparent);
  32.  
    //设置画布的描绘质量
  33.  
    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  34.  
    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  35.  
    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  36.  
    g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
  37.  
    g.Dispose();
  38.  
    //设置压缩质量
  39.  
    System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
  40.  
    long[] quality = new long[1];
  41.  
    quality[0] = 100;
  42.  
    System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
  43.  
    encoderParams.Param[0] = encoderParam;
  44.  
    sourImage.Dispose();
  45.  
    return destBitmap;
  46.  
    }
  47.  
    catch
  48.  
    {
  49.  
    return bitmap;
  50.  
    }
  51.  
    }
版权声明:本文为博主原创
posted @ 2018-07-10 15:41  😀垚,行者  阅读(697)  评论(1编辑  收藏  举报