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

回眸只為那壹抹淺笑 提交于 2019-11-29 16:54:59

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.

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

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