How does alpha blending work, mathematically, pixel-by-pixel?

流过昼夜 提交于 2020-01-10 05:54:48

问题


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



来源:https://stackoverflow.com/questions/10768836/how-does-alpha-blending-work-mathematically-pixel-by-pixel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!