开发者

Image Resize calculations - what's happening?

Can anyone shed any light on this issue please?

ASP.NET 4.0 / C#

The code:

Image image = Image.FromStream(Request.Files[0].InputStream);
var newWidth = 150;
var current = image.Width;
double scaleHeight = (150 / current);
if (scaleHeight == 0)
{
    scaleHeight = 0.2;
}
var newHeight = Convert.ToInt32(image.Height * scaleHeight);
var thumbnailBitmap = new Bitmap(newWidth, newHeight);
Graphics thumbnailGraph = Graphics.FromImage(thumbnailBitmap);

This code abov开发者_开发问答e always sets the scaleHeight as 0.2. Oddly the image.Width in the debugger is referencing the correct width of the image so logically 150 / x should give the decimal percentage 150 is of x, then I can workout a new height based on that percentage (height * result) - at least I think that's the math! hehe.

Eg: 150/1024==0.1464. Then 768 * 0.1464 == 112 (int) - 14% of 768 is approx 112. This doesn't work in the code - any ideas?

I'm clearly doing something stupidly wrong here, can anyone shed any light on this?

Sry for a daft question. Thanks for any help!

Chris.


This code above always sets the scaleHeight as 0.2

Careful with your var's. image.Width is an integer, so you are performing integer division here:

(150 / current);

If current is larger than 150 the result will always be 0. The act of assigning the result to a double does not mean that the result was not obtained using integer division. Try this:

double scaleHeight = (150.0 / current);

Of course, it really should be this:

double newWidth = 150;
var current = image.Width;
double scaleHeight = (newWidth / current);

As a side note, the 'var' keyword is great for reducing unnecessary verbosity in your code. However, I wouldn't get into the habit of declaring everything as 'var'. For one, it only serves to make your particular code snippet less clear. Secondly, you aren't really saving any typing (ok, a few more letters to type 'double', but you need that!). My advice would be to use 'var' only when it makes your code easier to read/understand due to there being less unnecessary verbosity. For simple things like declaring an int it isn't necessary and doesn't add any value.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜