如何在C#中调整保持纵横比的图像大小

Joh*_*iou 3 c# image

我需要知道一种方法来调整图像大小以适应盒子而不会使图像拉伸太多.盒子设置了宽度和高度,我希望图像尽可能多地填充盒子,但保持它原来的宽高比.

γηρ*_*όμε 10

//calculate the ratio
double dbl = (double)image.Width / (double)image.Height;

//set height of image to boxHeight and check if resulting width is less than boxWidth, 
//else set width of image to boxWidth and calculate new height
if( (int)((double)boxHeight * dbl) <= boxWidth )
{
    resizedImage = new Bitmap(original, (int)((double)boxHeight * dbl), boxHeight);
}
else
{
    resizedImage = new Bitmap(original, boxWidth, (int)((double)boxWidth / dbl) );
}
Run Code Online (Sandbox Code Playgroud)

使用相同比例缩放的公式为:

newWidth =  (int)((double)boxHeight * dbl)

or

newHeight =  (int)((double)boxWidth / dbl)
Run Code Online (Sandbox Code Playgroud)