1

I have a C programming background and I am used to doing ugly things.

Is there a more elegant/readable way to do this scaling operation in C#:

ImageProcessing.Resize(original, 80, (int)((float)original.Height * (80f / original.Width)));

Where "original" is the .Net Image class and Image.Width and Image.Height are thus integers.

John Shedletsky
  • 7,110
  • 12
  • 38
  • 63
  • 3
    These questions are better asked over at http://codereview.stackexchange.com/ – Ron Beyer Apr 30 '15 at 01:00
  • 4
    @RonBeyer One-liners are typically quite poor fits for [codereview.se]. – nhgrif Apr 30 '15 at 01:01
  • I didn't know that there was such a thing. – John Shedletsky Apr 30 '15 at 01:01
  • In either case, here's what you ask yourself, 1) Does it work? 2) Can my coworker read it and understand it? 3) Could it be refactored easily? I'm guessing #3 is yes, by breaking out the variables individually, the compiler will optimize it away anyway so don't be afraid to use more code to make things cleaner, especially with simple calculations like this. – Ron Beyer Apr 30 '15 at 01:03

2 Answers2

3

Regular division followed by the floor operation (cast to int) is equivalent to integer division. Multiplication and division are left-associative. Therefore you can use this much shorter code:

ImageProcessing.Resize(original, 80, 80 * original.Height / original.Width);

To convince you, suppose Width and Height are 300 and 200, respectively. Then your code will do this:

(int)(200f * (80f / 300f)) = (int)(200f * 0.2666...) = (int)(53.3333...) = 53

And my code will do this (where / denotes integer division):

80 * 200 / 300 = 16000 / 300 = 53
Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
  • 1
    Integer division in C# returns an int. For the scaling code to work, you need to do float division. http://stackoverflow.com/questions/10851273/why-integer-division-in-c-sharp-returns-an-integer-but-not-a-float – John Shedletsky Apr 30 '15 at 01:10
  • Maybe I should have added that original is of type Image and thus .Width and .Height are ints. – John Shedletsky Apr 30 '15 at 01:11
  • @JohnShedletsky Take a closer look at what I proposed and try it out. The multiplication happens before the division, so the scaling will in fact work fine. – Timothy Shields Apr 30 '15 at 01:11
  • Oh I see. I can never remember the association direction or operator precedence rules. – John Shedletsky Apr 30 '15 at 01:13
  • Yours is better in a tight loop as well. Probably way faster (10x?) to avoid the floating point math and the typecast. – John Shedletsky Apr 30 '15 at 01:24
0

If you want to change code (which looks ok): Since "w/h" is aspect ratio separately computing it may produce more self-documenting code:

var aspectRatio = original.Width / (float)original.Height;
int newWidth = 80;
ImageProcessing.Resize(original, newWidth, (int)(newWidth / aspectRatio));
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179