尝试调整尺寸时图像被拉伸以保持宽高比

时间:2018-06-26 08:32:59

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

我使用以下代码调整图像的大小,以保留宽高比

var tds = document.querySelectorAll("td[name]"); 
for (var i=0;i<tds.length;i++) {  
  tds[i].innerText=response[tds[i].getAttribute("name")]; 
}

但是宽宽度的图像会被压缩,内容似乎被打包在一个很小的空间中。我要达到的目的是: 调整大尺寸/大分辨率图像的大小,因为处理此过程将花费大量时间因此,当图像宽度或高度超过1000时,我想将图像调整为较小的尺寸,例如:1000宽度或高度较大,这样我可以节省计算时间。但是上述代码似乎是在强行尝试当我这样做时,将图像放入1000X1000盒子中

 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;
        }

1 个答案:

答案 0 :(得分:2)

尝试一下,它更整洁

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;
}