Increase rectangle by percentage

1.5k Views Asked by At

I'm programming a tool which scales images. The idea is to use a percentage of the actual megapixels. So if I had a picture 1200*1750 = 2.1 Mpx I'd like to get a 1.05 Mpx result when a decreasing percentage of 50% is given.

In order to do the resizing I have to find out the values of both sides. Theoretically I could multiply the sides while decreasing one side pixel by pixel, calculate the aspect ratio and stop when the desired percentage is reached. But this would resemble a try and error approach. Is there a more mathematical way of solving this? I couldn't find anything useful by googling.

1

There are 1 best solutions below

1
On BEST ANSWER

Say the picture you have has width $w$ and length $l$; then the total area would be $w\times l = A$.

Say you want to reduce the image by some percentage $P$, in decimal form. I assume you can convert percentages to and from decimals. So a $50\%$ reduction is $0.5$ and a $33.33333333(\dots)\%$ reduction is $0.3333(\dots)$

What does that mean? Well, if the new width and length are $w'$ and $l'$, it means we want

$$\frac{w'l'}{wl} = P$$

Also we know we want to scale the images down, so we could say that $w' = aw$ and $l' = bl$ for some values of $a,b$ you want to find out. If you want the aspect ratio to be the same, we need that $a = b$. Now, if we go to the last equation I wrote and substitute $w'$ by $aw$ and $l'$ by $al$ we get

$$\frac{a^2wl}{wl} = P \iff a^2 = P \iff a = \sqrt{P}$$

Therefore, if you want the new image to get $P\times 100\%$ of the size of the old one, just multiply each side by $\sqrt{P}$.

If you want to reduce the image to $50\%$ of the size, $P = 0.5$ and $\sqrt{P} \approx 0.707$. Or if you want to make the image have $400\%$ of the size, $P = 4 \implies \sqrt{P} = 2$, and you just multiply each side by $2$.