Calculating opacity value mathematically

spider picture spider · Jan 5, 2012 · Viewed 14.6k times · Source

How is opacity calculated mathematically?

There is opacity value in Photoshop, CSS etc. Actually this opacity is the transparent behavior of a layer. That we all know. But how is it calculated mathematically? Is there any equation to calculate opacity?

By setting opacity value what is happening there?

Take the case of plain color layers: Layer 1 (Foreground Layer) and Layer 2 (background layer)

Layer 1 is red (say color value A) and Layer 2 is white (say color value B).

When we set opacity (say p) to layer 1, we can put 0.5 or 50% and get a whitish red color (say color value X).

For getting this value X what should I do mathematically?

ie.

X = (things which will be a relation containing p, A and B)

I want to know the exact mathematical equation to find X.

Also if I have the equation, and color values are hexadecimal in nature, so with a hex calculator can I get a correct result?

Answer

ipavlic picture ipavlic · Jan 5, 2012

The formula for combining C1 = (R1,G1,B1) and C2 = (R2,G2,B2) into a new color C3, where C2 is overlayed on top of C1 with opacity p is usually ( (1-p)R1 + p*R2, (1-p)*G1 + p*G2, (1-p)*B1 + p*B2 ).

See Wikipedia article on transparency for more information.