How can I scale a value from -255 to 255 or -100 to 100 to a scale of 0-100?

2.5k Views Asked by At

For Brightness, I have a formula that takes in a value from -255 to 255 and contrast from -100 to 100. What if I wanted to use the same formula but I wanted to convert/adjust the scaling so that I take in a value from 0 to 100 but adjust it for brightness and contrast formula that has different scaling?

That is, e.g.

-255 to 255 and map it to a scale of 0 to 100.

2

There are 2 best solutions below

4
On BEST ANSWER

If I understand correctly you want a formula which scales numbers in the range $[-255,255]$ to numbers in the range $[0,100]$. Consider the points in the Cartesian plane $(-255,0), (255,100)$. Two points define a line. The equation of this line represents the conversion formula you are looking for.

So the slope is $\frac{\Delta y}{\Delta x} = \frac{100}{255-(-255)} = \frac{100}{510} = \frac{10}{51}$. Then letting $y = \frac{10}{51}x + b$ and plugging in $(-255,0)$, we get $0 = \frac{-2550}{51} + b \implies b = \frac{2550}{51} = 50$. So your formula is $y = \frac{10}{51}x + 50$.

1
On

In general, you can map the range $[a_1, b_1]$ to the range $[a_2, b_2]$ with a linear equation.

You need $f(a_1) = a_2$, and $f(b_1) = b_2$. Since we'll be using a linear equation, $f(x) = mx+c$, we get a system of equations:

\begin{align*} a_2 &= ma_1 + c \\ b_2 &= mb_1 + c \end{align*}

and we may subtract the second from the first, so that

$$a_2 - b_2 = m(a_1 - b_1),$$ in other words, $m = \frac{a_2 - b_2}{a_1 - b_1}.$ To find $c$, we can simply substitute our $m$-value in, to see that

\begin{align*} a_2 &= ma_1 + c\\ a_2 - ma_1 &= c.\\ \end{align*}

Thus, if you store the value $m = \frac{a_2 - b_2}{a_1 - b_1}$, your equation sending the interval $[a_1, a_2]$ to the interval $[a_2, b_2]$ will be given by

$$f(x) = mx + a_2 - ma_1 = m(x - a_1) + a_2 .$$