• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Height and Width proportional algorithm?

 
M Burke
Ranch Hand
Posts: 406
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am writing a method to resize images. I have that code working, but since the images can have variable width and height, I need to scale it.
Right now, if I tell the method I want the image to be scaled below 200 x 200, the image comes out distorted if its proportions are different.

So if I want the image to scale below width 200 and height 200, what formula would I use to get the new values?
 
Rob Spoor
Sheriff
Pie
Posts: 20661
64
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a ratio between the width and height. When you scale you must maintain that ratio. That means that the scale factor for the width and the height must be the same:
These two are the separate scale factors. You need to take one of those, and recalculate width and height from that factor and the original width and height. You then get a new width and height that have the same ratio.

Taking one of the factors will lead to an image where the width and height are at least the requested width and height (i.e. it fills the entire requested area). The other will lead to an image where the width and height are at most the requested width and height (i.e. it fits entirely inside the requested area). I'll let you experiment which will lead to which.
 
M Burke
Ranch Hand
Posts: 406
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see what you mean, Rob. So to finish the code I do this to get a width and height that fit within the confines of the max values.

double widthNew = heightFactor * srcWidth;
double heightNew = heightFactor * srcHeight;

I appreciate your help.
 
Rob Spoor
Sheriff
Pie
Posts: 20661
64
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That will work if heightFactor is the smaller of the two. If it's the larger of the two the image will fill instead of fit.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic