将未知大小的图像调整为特定大小而不变形?

resize an image with unknown size to a specific size without deformation?

我想从 Asp.net MVC 中的用户获取图像并将其调整为特定大小,但我必须将其调整为特定大小而不变形。如果图像的某些部分被裁剪,我没有问题,但我不希望用户上传 4000X2000px 图像我裁剪 600X600 并丢失图像的许多部分。

我该怎么做?有什么算法吗?或者.net 中有任何源代码吗?

我找到了解决方案:

               using (var bitmap = new Bitmap(image.InputStream))
                       {
                           var width = bitmap.Width;
                           var height = bitmap.Height;


                           double widthRatio = (double)600 / width;
                           double heightRatio = (double)600 / height;
                           double ratio = widthRatio > heightRatio ? widthRatio : heightRatio;


                           var resizedWidth = width < height ? 600 : (int)(width * ratio);
                           var resizedHeight = height < width ? 600 : (int) (height * ratio);


                           var converter = new ImageConverter();
                           var image =
                      new WebImage((byte[])converter.ConvertTo(bitmap, typeof(byte[])))
                      .Resize(resizedWidth, resizedHeight)
                      .Crop((resizedHeight - 600) / 2, ((resizedWidth - 600)/ 2), ((resizedHeight - 600) / 2), ((resizedWidth - 600) / 2));
          }