2010-03-26 67 views
1
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)
我obiously做错事与类型转换的图像?C#新手问题变量类型

+0

你得到了什么错误? – 2010-03-26 15:25:41

+0

'img1.Width'和'img1.Height'有什么值? – 2010-03-26 15:27:12

+0

@Präriewolf:我没有得到任何错误。 @PéterTörök:嗯...我不太确定,但我认为它是整数,因为我可以声明newWidth = img1.Width而没有错误。 – 2010-03-26 15:30:41

回答

12
ratio = img1.Width/img1.Height; 

宽度和高度都是整数。在将这些值存储在double中之前,您将对这些值执行整数运算。在整数数学中,150/100是1. 199/100是1.101/100是1.没有小数。在计算完值后,然后它将被存储在你的double中。

在进行计算之前,至少要将一边加倍。

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

嗯...现在我试图上传尺寸宽度= 800和高度= 533的新照片和缩略图是newWidth = 800和newHeight = 66 – 2010-03-26 15:35:47

+0

@ile,我不知道哪里会发生在你的代码片段中。你是否在上面不可见的地方设置了newWidth = img.Width?因为你不应该。 newWidth,从你的代码片段,应该保持100. – 2010-03-26 15:40:14

+0

upvoted这实际上是覆盖在我为基础考试我经历的毫秒压力机书籍之一,肯定需要施放其中一个数字(我通常做除数)来加倍避免精度损失。 – 2010-03-26 15:40:52

1

你可以说:

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

为了保证结果的值不被截断由于整数运算。

+1

就我个人而言,我认为铸造(ala @ Anthony的答案)使意图更清晰。 – JeffH 2010-03-26 15:34:24

0

图像的大小是多少?如果宽度和高度总是相等,那么这是有道理的。

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

高度和宽度不一样。我测试水平和垂直的照片 – 2010-03-26 15:34:24