Resizing and scaling image

7.4k Views Asked by At

I'm trying to resize image bitmap in software development, in that my requirement is as following,

  • Get the original height of image
  • Get the original width of image
  • Set a max threshold, output height and width should be below that threshold only

My requirement is,

  • output height and width should be below set threshold
  • output values should be maximum possible
  • The ratio of final height and width should be same as original.

I am new to this community, so pardon me if anything is incorrect, any help will be appreciate.

3

There are 3 best solutions below

2
On BEST ANSWER

The maths is quite simple

  1. Calculate the ratio between the width and height
  2. Set the width to be equal to the limit
  3. Calculate the height based on the ratio previously calculated
  4. If the height exceeds the limit, then repeat steps (2) and (3) using the height instead

For example, say you have an image with $\text{width}=6$ and $\text{height}=9$ and your threshold is $15$

The ratio between width and height is $2:3$, in other words, $$\text{width}=\frac 23\times \text{height}$$

If we increase the width to be equal to the limit, $15$, then our height becomes $$15\times \frac32 = 22.5$$

As this is above the limit of $15$, we instead set the height to be $15$ which gives us a width of $$15\times \frac 23 = 10$$

This is inside our limit so we have a new image with $\text{width}=10$ and $\text{height}=15$, which still obeys our $2:3$ ratio and is within the threshold.

0
On

So, essentially you have numbers $(w, h)$ and you want to scale them so that $\max{(w_{\text{new}}, h_{\text{new}})}=M$, some maximum value. You simply have to calculate $$ (w_{\text{new}}, h_{\text{new}}) = \frac{M}{\max{(w,h)}} (w,h) $$ You can see that doing so replaces the bigger value by $M$ and scales the other by the same ratio. Done.

0
On

Let your image have size $w \times h$, $t$ be the threshold, and $r=\frac{w}{h}$ be the ratio. If $t>\max(w,h)$ do nothing. Let $w\geq h$. You want to find a linear mapping $f : [0,w] \rightarrow [0,t]$, that is $f(x) = ax + b, f(0) = 0, f(w) = t$, from the first condition $b= 0$, from the second $a=\frac{t}{w}$. The new width is $w'= t$, since we want to preserve the ratio: $r=\frac{w'}{h'}$, then $h' = \frac{w'}{r}$. The mapping for $y$ can similarly be computed as: $g(y) = \frac{h'y}{h}$. Your new image has dimensions $w' \times h'$. Then for every point in the image $(x,y)$, the new transformed coordinates are $(x',y') = (\frac{w'x}{w}, \frac{h'y}{h})$. In case $w<h$, $h'=t, w' = rh'$.