How does alpha blending work, mathematically, pixe

2019-03-06 08:50发布

问题:

Seems like it's not as simple as RGB1*A1 + RGB2*A2...how are values clipped? Weighted? Etc.

And is this a context-dependent question? Are there different algorithms, that produce different results? Or one standard implementation?

I'm particularly interested in OpenGL-specific answers, but context from other environments is useful too.

回答1:

I don't know about OpenGL, but one pixel of opacity A is usually drawn on another pixel like so:

result.r = background.r * (1 - A) + foreground.r * A
result.g = background.g * (1 - A) + foreground.g * A
result.b = background.b * (1 - A) + foreground.b * A

Repeat this operation for multiple pixels.



回答2:

The above answer works if the image isn't premultiplied alpha. However if you use that type of blending with a premultiplied alpha image, there will be a black border.

Premultiplied Alpha:

When the image is created, the color values are multiplied by the alpha channel. Take a look at this one pixel example:

Pixel: r = 1, g = 0, b = 0, a = 0.5

When it's saved, the rgb vales will be multiplied by the alpha value giving:

Pixel: r = 0.5, g = 0, b = 0, a = 0.5

To blend this kind of image you need to use the following formula:

result.r = background.r * (1 - A) + foreground.r
result.g = background.g * (1 - A) + foreground.g
result.b = background.b * (1 - A) + foreground.b

Non-premultiplied Alpha

In this example, the alpha channel is completely separate to the color channels.

Pixel: r = 1, g = 0, b = 0, a = 0.5

When it's saved:

Pixel: r = 1, g = 0, b = 0, a = 0.5

It's the same. In this case the answer provided by minitech is correct.

More details can be found here: Premultiplied alpha