Win a copy of Design for the Mind this week in the Design forum!

# Height and Width proportional algorithm?

M Burke
Ranch Hand
Posts: 401
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
Posts: 20512
54
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: 401
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
Posts: 20512
54
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.