## Saturday, October 3, 2015

### TIL: premultiplied-alpha colors

Alpha is the measure of how translucent an object is. An alpha of 0.0 means the object is entirely transparent, an alpha of 1.0 means the object is entirely opaque, and an alpha in the middle means a fraction of the total light may passthrough the object. Traditionally, a color is represented by 4 constituent components: a red contribution, a green contribution, a blue contribution, and the alpha. When compositing two colors together, one on top of the other, the alpha acts as a modulus of the colors, indicating how much of the top color and how much of the bottom color contribute to the new composited color. The traditional compositing operation is as follows, where A is being composited over top B:

$\inline&space;\\&space;A&space;=&space;\begin{bmatrix}&space;r_{a}&space;&&space;g_{a}&space;&&space;b_{a}&space;&&space;a_{a}&space;\end{bmatrix}&space;\\&space;B&space;=&space;\begin{bmatrix}&space;r_{b}&space;&&space;g_{b}&space;&&space;b_{b}&space;&&space;a_{b}&space;\end{bmatrix}&space;\\&space;C_{rgb}&space;=&space;a_{a}\cdot&space;A_{rgb}&space;+&space;(1&space;-&space;a_{a})\cdot&space;B_{rgb}$

Alternatively, we may wish to premultiply the red, green, and blue components by the alpha:

$C&space;=&space;\begin{bmatrix}&space;a\cdot&space;r&space;&&space;a\cdot&space;g&space;&&space;a\cdot&space;b&space;&&space;a\end{bmatrix}$

With this representation we get a new compositing equation:

$C&space;=&space;A&space;+&space;(1&space;-&space;a_{A})\cdot&space;B$

This new form is interesting for a couple reasons.
1. It is computationally more efficient. It requires one less vector multiplication.
2. It is a closed form. Compositing a premultiplied-alpha color over top a premultiplied-alpha color yields another premultiplied-alpha color. The same cannot be said of non-premultiplied-alpha colors. Compositing two non-premultiplied-alpha colors yields, interestingly, a premultiplied-alpha color.
3. When filtering (aka downsampling), it produces more visually accurate results. A picture is worth a thousands words.
And that's it. Premutliplied-alpha colors are nifty.