[Math] How to resize an image

algebra-precalculusimage processing

I am not sure about the title of this question, so if someone knows an appropriate one, please rename it. It's a programming related question (but doesn't involve any programming). I posted it on stack overflow but didn't get any responses so I am trying here.

I need to map a piece of rectangle (x, y, width, height) of an (original)image onto a canvas by resizing the original image. Here's a picture that explain it better.
enter image description here

Here's another one, bit different, so you get a better idea:

enter image description here

I can scale and move the image however I want. How do i figure out the scale at which to resize the original image.

I had an idea, which was to figure the bigger dimension of the given rectangle, and use that to figure out the scale, so:

Given: imageWidth, imageHeight, rectWidth, rectHeight, canvasWidth, canvasHeight (let's ignore the offsets for now)

But that doesn't work in some cases. So I wondering what's the best way to do this.
,

Best Answer

If I understand your question correctly then you need to do this:

scaleVert:=(rectHeight/rectWidth > canvasHeight/canvasWidth);
if scaleVert then
  scale:=canvasHeight/rectHeight
else
  slace:=canvasWidth/rectWidth;

The value of scale is ratio by which you have to scale your image.

The Boolean variable scaleVert is used to test whether you have to fit your rectangle vertically (i.e., the height of rectangle after scaling will be the same as the height of the canvas) or horizontally.


Notice that if rectHeight/rectWidth = canvasHeight/canvasWidth then it does not matter whether you scale vertically or horizontally - you obtain the same result. (The two rectangles are similar.)

If the rectangle is "thinner" (i.e., the ratio rectHeight/rectWidth is higher) you have to scale vertically and otherwise you have to scale horizontally.