【问题标题】:Image Getting Stretched when trying to Resize It keeping the aspect Ratio尝试调整大小时图像被拉伸保持纵横比
【发布时间】:2018-12-04 21:47:54
【问题描述】:

我使用以下代码来调整图像大小并保留纵横比

 public Bitmap resizeImage(System.Drawing.Image imgToResize, SizeF size)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);

            // Used to Prevent White Line Border 

           // g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();

            return b;
        }

但是大宽度的图像被压缩并且内容似乎被打包到一个小空间中。我试图实现的是:调整大尺寸/大分辨率图像的大小,因为处理这将花费大量时间,所以当图像宽度或高度超过 1000 时,我想将图像调整为更小的尺寸,例如:1000 宽度或高度,哪个更大,这样我可以节省计算时间。但似乎上面的代码是强行尝试当我这样做时,将图像放入 1000X1000 框

if (y.Width > 1000 || y.Height > 1000)
{

y = new Bitmap( resizeImage(y, new Size(1000, 1000)));

}

【问题讨论】:

  • 你调试过这个吗?
  • 您必须确定图像应调整大小的比例,并根据该计算设置新尺寸。
  • @TheGeneral 其实我在调用另一个带整数参数的方法,应该是resizeImage(y, new Size(1000, 1000))

标签: c# .net bitmap gdi+ system.drawing


【解决方案1】:

试试这个,它更整洁一些

public static Bitmap ResizeImage(Bitmap source, Size size)
{
   var scale = Math.Min(size.Width / (double)source.Width, size.Height / (double)source.Height);   
   var bmp = new Bitmap((int)(source.Width * scale), (int)(source.Height * scale));

   using (var graph = Graphics.FromImage(bmp))
   {
      graph.InterpolationMode = InterpolationMode.High;
      graph.CompositingQuality = CompositingQuality.HighQuality;
      graph.SmoothingMode = SmoothingMode.AntiAlias;
      graph.DrawImage(source, 0, 0, bmp.Width, bmp.Height);
   }
   return bmp;
}

【讨论】:

  • 感谢您的回答。将检查并恢复。
猜你喜欢
  • 2013-06-26
  • 2012-04-15
  • 2012-05-01
  • 2012-11-15
  • 2019-08-15
相关资源
最近更新 更多