Source-over compositing (source code)

= Source-over compositing

\b[Source-over compositing] combines a source layer with a background by retaining the source contribution and the fraction of the background left by the source's <alpha channel>. For <premultiplied alpha> colour triples $c_s=\alpha_sC_s$ and $c_b=\alpha_bC_b$, the rule is
$$
c_o=c_s+(1-\alpha_s)c_b,\qquad
\alpha_o=\alpha_s+(1-\alpha_s)\alpha_b.
$$
The W3C compositing specification states this operator explicitly.<Compositing and Blending Level 1 by World Wide Web Consortium>[2024Candidate Recommendation Draft, §9.1.4, Source Over; §5.1, premultiplied output and output alpha]{ref} The output is another colour-and-alpha pair, so it can be combined with another layer.

For an original <Linear-light RGB> example, take red layer A with alpha $1/2$, green layer B with alpha $1/4$, and blue layer C with alpha $1/2$. Place A over B over C. Expanding <source-over compositing> gives
$$
c_o=c_A+(1-\alpha_A)c_B+(1-\alpha_A)(1-\alpha_B)c_C
=(1/2,1/8,3/16),
$$
with $\alpha_o=1-(1-\alpha_A)(1-\alpha_B)(1-\alpha_C)=13/16$. Its <straight alpha> colour is therefore $(8/13,2/13,3/13)$. The colour triple alone does not describe the partly transparent output; the alpha must accompany it.

The expansion also proves <associativity> in exact arithmetic: grouping A over B first or grouping B over C first produces those same three terms. Reordering the layers changes the coefficients, so <associativity> does not permit exchanging front and back. Intermediate rounding can introduce small numerical differences even when the mathematical grouping is equivalent.

For fully transparent source alpha zero, <source-over compositing> retains the background; for opaque source alpha one, it retains only the source. To interpret the colour arithmetic as a mixture of light contributions, use a common <Linear-light RGB> space. Stored <sRGB> codes generally need decoding first.<Portable Network Graphics (PNG) Specification (Third Edition) by Mark Adler and others>[§13.16, alpha channel processing and gamma correction]{ref} Apply the equation for the actual storage convention: treating <premultiplied alpha> samples as <straight alpha> samples multiplies the source contribution twice.