Search code examples
graphicscolorsalphablending

How are the blended colors computed in this case?


This is a question about expected results of alpha blending.

Here is the setup: Background color is transparent black (0, 0, 0, 0.18). Drawing color is semi-transparent green (0, 1, 0, 0.5).

This is the result in a graphics editor (GIMP):

colors

The resulting color is (0, 0.93, 0, 0.59).

If we blend these colors with color blend formula C1 * (1 - A2) + C2 * A2 and calculate alpha A1 * (1 - A2) + A2 we get (0, 0.5, 0, 0.59).

Alpha is correct, colors are not. Output color is grayish green. That becomes very noticeable on white background.

What is wrong here? Do editors use different blending formulas (then what they are)? Am I wrong in my calculations?


Solution

  • First of all, if I create an image like yours, I get the final color (0, 0.863, 0, 0.59). So you might want to check your input.

    Blending colors is a bit tricky. The formula you showed (C1 * (1 - A2) + C2 * A2) is the formula for blending a color over a solid background color. But we do not have a solid background color. What we want to do is find a blended color (C, A) such that this color blended over any solid background color CB produces the same result as first blending (C1, A1) over the background and then (C2, A2) over the resulting color. We can express that in the following equation:

    A * C + (1 - A) * CB = A2 * C2 + (1 - A2) * (A1 * C1 + (1 - A1) * CB)
    

    After some re-arranging:

    A * C - A * CB = A2 * C2 + A1 * C1 - A2 * A1 * C1 + (A1 * A2 - A1 - A2) * CB
    

    From this, we see that the two factors of CB must match on the two sides, i.e.

    - A = A1 * A2 - A1 - A2
    

    And hence

    A = A1 + A2 - A1 * A2
    

    And the color equates to

    A * C = A2 * C2 + A1 * C1 - A2 * A1 * C1
        C = (A2 * C2 + A1 * C1 - A2 * A1 * C1) / A
    

    In this case, this evaluates to 0.847. There is still a slight difference to the observed value of 0.866, but I would consider this a rounding error.

    Also note that GIMP has two compositing modes. A linear-RGB mode and a perceptual mode. The perceptual mode presumably performs the blending in a gamma-corrected space.