6

If I have an RGB color, with 100% opacity.

I want that same color (or close to it) with a transparent alpha channel. I will paint the transparent color over a white background.

How do I compute the RGBA color?

I guess what I am asking is the opposite of this question.

Community
  • 1
  • 1
jedierikb
  • 12,752
  • 22
  • 95
  • 166

1 Answers1

5

You mean you want the RGBA color with maximum transparency which, when drawn on top of a white background, gives the original RGB color?

Let R0, G0 and B0 be the components of the original color, each ranging from 0.0 to 1.0, and let R, G, B and A be the components of the new RGBA color (with A = 1 denoting 100% opacity). We know that the colors must satisfy:

R0 = A·R + (1 − A)
G0 = A·G + (1 − A)
B0 = A·B + (1 − A)

which, if we knew A, we could easily solve for R, G and B:

R = (R0 − 1 + A) / A = 1 − (1 − R0) / A
G = (G0 − 1 + A) / A = 1 − (1 − G0) / A
B = (B0 − 1 + A) / A = 1 − (1 − B0) / A

Since we require that R ≥ 0, G ≥ 0 and B ≥ 0, it follows that 1 − R0 ≥ A, 1 − G0 ≥ A and 1 − B0 ≥ A, and therefore the smallest possible value for A is:

A = max( 1 − R0, 1 − G0, 1 − B0 ) = 1 − min( R0, G0, B0 )

Thus, the color we want is:

A = 1 − min( R0, G0, B0 )
R = 1 − (1 − R0) / A
G = 1 − (1 − G0) / A
B = 1 − (1 − B0) / A


Ps. For a black background, the same formulas would be even simpler:

A = max( R0, G0, B0 )
R = R0 / A
G = G0 / A
B = B0 / A


Pps. Just to clarify, all the formulas above are for non-premultiplied RGBA colors. For premultiplied alpha, just multiply R, G and B as calculated above by A, giving:

R = A · ( 1 − (1 − R0) / A ) = R0 − (1 − A)
G = A · ( 1 − (1 − G0) / A ) = G0 − (1 − A)
B = A · ( 1 − (1 − B0) / A ) = B0 − (1 − A)

(or, for a black background, simply R = R0, G = G0 and B = B0.)

Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
  • Thank you! So this solves for max alpha... Is there a formula for min alpha (and, Pushing my luck, the range between)? – jedierikb Dec 28 '12 at 06:33
  • 1
    @jedierikb: Um... The alpha value given above _is_ the minimum. The maximum is _A_ = 1, with _R_ = _R0_, _G_ = _G0_ and _B_ = _B0_. (And yes, you can interpolate between those: just pick any valid alpha value and use the formulas above to get _R_, _G_ and _B_.) – Ilmari Karonen Dec 28 '12 at 18:03