如何在C#中调整保持纵横比的图像大小 [英] How to resize an image maintaining the aspect ratio in C#

查看:706
本文介绍了如何在C#中调整保持纵横比的图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to know of a way to resize an image to fit in a box without the image stretching too much. The box has set width and height and I want the image to fill as much of the box as possible but maintain the aspect ratio it originally had.

推荐答案

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

使用相同比率进行缩放的公式为:

The formula for scaling with the same ratio is:

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

or

newHeight =  (int)((double)boxWidth / dbl)

这篇关于如何在C#中调整保持纵横比的图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆