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

前端 未结 2 1417
执笔经年
执笔经年 2020-12-22 00:39

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 algorit

相关标签:
2条回答
  • 2020-12-22 01:10

    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.

    0 讨论(0)
  • 2020-12-22 01:11

    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

    0 讨论(0)
提交回复
热议问题