【问题标题】:C# newbie problem with variable types变量类型的C#新手问题
【发布时间】:2011-02-01 05:38:20
【问题描述】:
int newWidth = 100;
int newHeight = 100;
double ratio = 0;

if (img1.Width > img1.Height)
{
    ratio = img1.Width / img1.Height;
    newHeight = (int)(newHeight / ratio);
}
else
{
    ratio = img1.Height / img1.Width;
    newWidth = (int)(newWidth / ratio);
}

Image bmp1 = img1.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
bmp1.Save(Server.MapPath("~/Uploads/Photos/Thumbnails/") + photo.PhotoID + ".jpg");

我总是得到高度和宽度具有相同值的图像 (100)
我在类型转换方面明显做错了什么?

【问题讨论】:

  • img1.Widthimg1.Height 有什么值?
  • @Präriewolf:我没有收到任何错误。 @PéterTörök:嗯...我不太确定,但我认为它是整数,因为我可以毫无错误地声明 newWidth = img1.Width。
  • 你能举一些你正在测试的图片尺寸的例子吗?
  • width=800 和 height=533

标签: c# integer double type-conversion


【解决方案1】:
ratio = img1.Width / img1.Height;

宽度和高度是整数。在将它们存储到双精度值之前,您将对这些值执行整数数学运算。在整数数学中,150 / 100 是 1。199 / 100 是 1。101 / 100 是 1。没有小数。计算完值后,然后它将存储在您的双精度数中。

在进行计算之前,至少将一侧翻倍。

ratio = img1.Width / (double)img1.Height;

【讨论】:

  • 嗯...现在我尝试上传尺寸为 width=800 和 height=533 的新照片,缩略图为 newWidth=800 和 newHeight=66
  • @ile,我看不出在你的代码 sn-p 中会发生什么。您是否在上面不可见的任何地方设置 newWidth = img.Width ?因为你不应该。 newWidth,来自您的 sn-p,应保持 100。
  • 赞成这实际上包含在我为基础考试而阅读的一本 ms 新闻书籍中,肯定需要将其中一个数字(我通常做除数)加倍以避免精度损失.
  • 你能用调试器单步调试代码,看看 newWidth 何时变为 800 吗?
  • 安东尼,你是对的!我在 if 语句下方留下了 newWidth = img.Width 并忘记将其删除。谢谢!
【解决方案2】:

你可以说:

ratio = img1.Width / (img1.Height * 1.0);

确保结果的值不会因为整数运算而被截断。

【讨论】:

  • 就个人而言,我认为选角(ala @Anthony 的回答)使意图更加清晰。
【解决方案3】:

图片的尺寸是多少?如果宽度和高度始终相等,那么这是有道理的。

newWidth = (int)(newWidth / ratio);  // this is newWidth = newWidth / 1 so it doesn't change.

【讨论】:

  • 高度和宽度不一样。我测试水平和垂直照片
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-03
  • 2011-02-17
  • 1970-01-01
  • 2011-08-08
  • 2015-11-27
  • 1970-01-01
  • 2011-06-05
相关资源
最近更新 更多