[英]C# Image Resize Math Issue
So I have a simple bit of code that re-sizes my profile images as they are consumed, problem is, the C# code isn't working the way I expected... 因此,我有一些简单的代码可以在使用我的个人资料图像时调整其大小,问题是C#代码无法按我预期的方式工作...
Here's the bit of code inside of the Controller Action Method for the Index View, where I'm doing this... 这是索引视图的Controller Action方法中的一些代码,我在这里执行此操作...
string fullFileName = HttpContext.Server.MapPath(profile.ProfilePhotoPath);
System.Drawing.Image img = System.Drawing.Image.FromFile(fullFileName);
int width = img.Width;
int height = img.Height;
float reductionPercentage = 0F;
if (width >= height)
{
reductionPercentage = (282 / width);
}
if (width < height)
{
reductionPercentage = (337 / height);
}
int newWidth = (int)Math.Round(width * reductionPercentage);
int newHeight = (int)Math.Round(height * reductionPercentage);
ViewBag.newWidth = newWidth;
ViewBag.newHeight = newHeight;
Every part of this works perfectly, except when it hits the "reductionPercentage = * " 除达到“ reductionPercentage = * ”外,此过程的每个部分均正常运行
If the image is smaller or the same size, the reductionPercentage does exactly as it should and assign the value 1 to the reductionPercentage, however, if the image is larger, it's like it doesn't do the math at all, it always spits out 0 as the value for the reductionPercentage... 如果图像较小或相同大小,则reductionPercentage会按照其应有的方式进行操作,并为reductionPercentage分配值1,但是,如果图像较大,就好像它根本不进行数学运算一样,总是吐出0为reductionPercentage ...的值
Any ideas, what could I possibly doing wrong? 有什么想法,我可能做错什么?
(282 / width)
and (337 / height)
are integer division - when the denominator is larger than the numerator, you will get 0
as a result. (282 / width)
和(337 / height)
是整数除法 -当分母大于分子时,结果将为0
。
Make one of the division participants a float to ensure floating point division. 使除法参与者之一成为浮点数,以确保浮点除法。
if (width >= height)
{
reductionPercentage = (282f / width);
}
if (width < height)
{
reductionPercentage = (337f / height);
}
Because 282
, 337
, width
, and height
are all integers, the /
operator performs an integer division, truncating any fractional part of the result. 因为
282
, 337
, width
,和height
均为整数,所述/
操作者进行整数除法,截断结果的任何小数部分。 Use 282f
and 337f
instead: 请改用
282f
和337f
:
if (width >= height)
{
reductionPercentage = 282f / width;
}
else
{
reductionPercentage = 337f / height;
}
The f
suffix signals that the number is a float
instead of an int
, so that a floating-point division is performed. 后缀
f
表示该数字是float
而不是int
,因此执行浮点除法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.