开发者

C# newbie problem with variable types

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");

I always get Image with both height and width having same values (100)

I am obiously doing something wrong with type conversion?


ratio = img1.Width / img1.Height;

Width and Height are integers. You will be performing integer math on these values before storing them in your double. In integer math, 150 / 100 is 1. 199 / 100 is 1. 101 / 100 is 1. There are no decimals. After the value has been calculated, then it will be stored in your double.

Cast at least one side to double before doing your calculation.

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


You can say:

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

To ensure that the value of the result is not truncated due to integer arithmetic.


What is the size of the images? if the width and height are always equal then this would make sense.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜