zoukankan      html  css  js  c++  java
  • 等比例缩放图片(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.  
      }
    版权声明:本文为博主原创
  • 相关阅读:
    Caliburn.Micro学习笔记(四)----IHandle<T>实现多语言功能
    linux irq 自动探测
    gpio子系统和pinctrl子系统(下)
    gpio子系统和pinctrl子系统(中)
    gpio子系统和pinctrl子系统(上)
    linux驱动基础系列--linux spi驱动框架分析
    linux驱动基础系列--linux rtc子系统
    linux驱动基础系列--Linux I2c驱动分析
    camera驱动框架分析(上)
    camera驱动框架分析(中)
  • 原文地址:https://www.cnblogs.com/zhangyao-950907/p/9289432.html
Copyright © 2011-2022 走看看