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.  
      }
    版权声明:本文为博主原创
  • 相关阅读:
    Quartz.Net进阶之一:初识Job作业和触发器
    Sql Server 三个很有用的函数
    Quartz.NET快速入门指南
    VS2015 提示 无法启动 IIS Express Web 服务器
    sql like 另一个表的字段
    Python3快速入门--Python多线程编程
    seo-网站变化百度搜索引擎的影响
    Asp.NetCore 3.1 EFCore处理Mysql的分库分表--MyCat解决方案
    asp.net core 3.1里 EF的事务-代码示例
    Asp.netCore3.1 Blazor入门
  • 原文地址:https://www.cnblogs.com/zhangyao-950907/p/9289432.html
Copyright © 2011-2022 走看看