How to resize an image?

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.

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

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. ,

-
It looks like $imageHeight=rectHeight$. So just consider the ratio $\lambda=canvasHeight/imageHeight$. If you scale the image by $\lambda$ in both directions, then the height of the scaled image will now be $canvasHeight$. Is this what you mean? – dls Aug 9 '12 at 4:17
Please check out the new image I uploaded. I am looking for a general solution, to figure out, exactly which dimension dictates the scale. – PragmaOnce Aug 9 '12 at 4:26

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

scaleVert:=(rectHeight/rectWidht > 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/rectWidht = 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/rectWidht is higher) you have to scale vertically and otherwise you have to scale horizontally.

-
Thanks for this, will try it out. Also, if got a moment, can you explain why scaleVert simply can't be 'rectHeight > rectWidth'? – PragmaOnce Aug 9 '12 at 5:01
@PragmaOnce I've added a few lines of explanation to my post. – Martin Sleziak Aug 9 '12 at 5:04
Thanks! Works perfectly. Appreciate your explanation. – PragmaOnce Aug 9 '12 at 5:59