我被要求将任何图片缩小为相应的缩略图,同时保持图片的原始宽高比。
到目前为止,我只能通过传递最大宽度来实现这一点,如下所示:
public static Size GetSizeAdjustedToAspectRatio(int sourceWidth, int sourceHeight, int dWidth, int dHeight)
{
bool isLandscape = sourceWidth > sourceHeight;
int fixedSize = dWidth;
double aspectRatio = (double)sourceWidth / (double)sourceHeight; ;
if (isLandscape)
return new Size(fixedSize, (int)((fixedSize / aspectRatio) + 0.5));
else
return new Size((int)((fixedSize * aspectRatio) + 0.5), fixedSize);
}
我尝试了几种计算方法,以便它能接受任何给定的最大高度和最大宽度,以保持最终结果图片的原始纵横比。
int
的强制转换就足够了。如果你想要获得特定的行为,请依赖于一个函数(Math.Round
或者Math.Ceiling
/Math.Floor
)。 - undefined