简体   繁体   English

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

[英]Image Getting Stretched when trying to Resize It keeping the aspect Ratio

Im using the following code to resize an image preserving the aspect ratio 我使用以下代码来调整图像的大小,以保留宽高比

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

But images with large width gets compressed and the contents seem packed up into a small space.What im trying to achieve is this : Resize the Large Size/Large Resolution image because processing this will take huge time,So when the image width or height exceeds say 1000 i want to resize the image to a Smaller size eg:1000 Width or Height which ever is larger,so that i can save computation time.But it seems the above code is forcibly trying to fit the image into the 1000X1000 Box when i do 但是大宽度的图像会被压缩,内容似乎被压缩在一个很小的空间中。我要达到的目的是: 调整大尺寸/大分辨率图像的尺寸,因为处理此过程将花费大量时间,因此当图像的宽度或高度超过说1000我想将图像调整为较小的尺寸,例如:1000宽度或高度较大,这样我可以节省计算时间。但是,似乎上面的代码是在我试图将图像适合1000X1000 Box时强行尝试做

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

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

}

Try this, its a bit neater 试试这个,有点整洁

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM