-1

Okay I know it sounds like it's a repost of another question, but I couldn't find anybody asking the same question as I do, or maybe I'm wrong because that's not the way how to handle the problem, but anyway here it comes:

I have an input image, say HD 1920*1080 and I just know a scale factor: say, 0.3 ( 30% of original size). How would one compute the new target size that is close to 30% of the original, while keeping the aspect ratio ? In other words how to rescale the image to 30% accurately?

If this makes no sense, please could you enlighten me about how to scale an image without knowing the target size and just knowing a scale factor?

Thanks

Ps: I'm using C/C++, but pseudo-code is okay

Lex
  • 413
  • 1
  • 7
  • 19

1 Answers1

3

If your height & width are integers, you can just do this...

height = height * (int)(scaleFactor*100) / 100;
width  = width  * (int)(scaleFactor*100) / 100;

Alternatively, this solution also works for int but makes more sense with floating point vars...

height = floor(height * scaleFactor);
width  = floor(width  * scaleFactor);

Or, regardless of the variable types, you can just let the compiler worry about how to handle the rounding...

height = height * scaleFactor;
width  = width  * scaleFactor;

...but with that solution, you may get off-by-1 rounding errors from one platform to the next. That may not matter in your use case, though.

Another possibility, if your scaleFactor is itself an int and (in this example) is 30%, then scaleFactor could be the value 30, and you'd simply do this...

height = height * scaleFactor / 100;
width  = width  * scaleFactor / 100;

The key is that if you scale both your x & y coordinates by the same factor, you preserve the original aspect ratio.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
phonetagger
  • 7,701
  • 3
  • 31
  • 55
  • thanks for your answer I'm going to try it – Lex Jan 24 '13 at 20:06
  • @Lex, my favorite, not listed here, would include some rounding and enforcing a minimum value: `height = max(1, (int)(height * scaleFactor + 0.5));` – Mark Ransom Jan 24 '13 at 20:06
  • thanks Mark, +0.5 is for rounding to nearest greater integer , right? – Lex Jan 24 '13 at 20:10
  • @Lex - I believe that's what Mark Ransom's suggestion's `+0.5` is for. I don't actually think it matters that much when the difference is a single pixel, unless your resulting image is going to be really small, the difference is negligible. But I suppose enforcing a minimum of 1 pixel might avoid divide-by-zero crashes in some cases. – phonetagger Jan 24 '13 at 20:12
  • @MarkRansom - Thanks for fixing my typos. – phonetagger Jan 24 '13 at 20:13
  • @Lex, yes +0.5 is to round to nearest rather than to floor. And phonetagger, you're welcome. – Mark Ransom Jan 24 '13 at 20:19