等比例缩放图片(C#)

  1. private Bitmap ZoomImage(Bitmap bitmap, int destHeight, int destWidth)  
  2. {  
  3.     try  
  4.     {  
  5.         System.Drawing.Image sourImage = bitmap;  
  6.         int width = 0, height = 0;  
  7.         //按比例缩放             
  8.         int sourWidth = sourImage.Width;  
  9.         int sourHeight = sourImage.Height;  
  10.         if (sourHeight > destHeight || sourWidth > destWidth)  
  11.         {  
  12.             if ((sourWidth * destHeight) > (sourHeight * destWidth))  
  13.             {  
  14.                 width = destWidth;  
  15.                 height = (destWidth * sourHeight) / sourWidth;  
  16.             }  
  17.             else  
  18.             {  
  19.                 height = destHeight;  
  20.                 width = (sourWidth * destHeight) / sourHeight;  
  21.             }  
  22.         }  
  23.         else  
  24.         {  
  25.             width = sourWidth;  
  26.             height = sourHeight;  
  27.         }  
  28.         Bitmap destBitmap = new Bitmap(destWidth, destHeight);  
  29.         Graphics g = Graphics.FromImage(destBitmap);  
  30.         g.Clear(Color.Transparent);  
  31.         //设置画布的描绘质量           
  32.         g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;  
  33.         g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;  
  34.         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;  
  35.         g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);  
  36.         g.Dispose();  
  37.         //设置压缩质量       
  38.         System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();  
  39.         long[] quality = new long[1];  
  40.         quality[0] = 100;  
  41.         System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);  
  42.         encoderParams.Param[0] = encoderParam;  
  43.         sourImage.Dispose();  
  44.         return destBitmap;  
  45.     }  
  46.     catch  
  47.     {  
  48.         return bitmap;  
  49.     }  
  50. }  

猜你喜欢

转载自www.cnblogs.com/password1/p/8968952.html