且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将RGBA颜色转换为RGB

更新时间:2022-06-11 00:15:43

我已经考虑过Johannes的回答,因为他是对的。

I've upvoted Johannes' answer because he's right about that.

被提出我的原始答案是不正确的。如果alpha值从正常反转,它工作。然而,根据定义,这在大多数情况下不起作用。因此,我更新了下面的公式正确的正常情况。这最终等于@ hkurabko的回答下面*

然而,更具体的答案将alpha值合并到基于不透明的实际颜色结果

A more specific answer, however, incorporates the alpha value into the actual colour result based on an opaque background colour (or 'matte' as it's referred to).

这里有一个算法(来自***链接):

There is an algorithm for this (from this wikipedia link):


  • 规范化RGBA值, 're all在0和1之间 - 只是每个值除以255这样做。我们将调用结果 Source

  • 标准化遮罩颜色(黑色,白色)。我们将调用结果 BGColor 注意 - 如果背景颜色也是透明的,那么您必须先对其进行递归

  • 现在,转换被定义为(完整的伪代码在这里!):

  • Normalise the RGBA values so that they're all between 0 and 1 - just divide each value by 255 to do this. We'll call the result Source.
  • Normalise also the matte colour (black, white whatever). We'll call the result BGColor Note - if the background colour is also transparent, then you'll have to recurse the process for that first (again, choosing a matte) to get the source RGB for this operation.
  • Now, the conversion is defined as (in complete psuedo code here!):

Source => Target = (BGColor + Source) =
Target.R = ((1 - Source.A) * BGColor.R) + (Source.A * Source.R)
Target.G = ((1 - Source.A) * BGColor.G) + (Source.A * Source.G)
Target.B = ((1 - Source.A) * BGColor.B) + (Source.A * Source.B)


对于 Target ,您只需将所有规范化值乘以255,确保如果任何组合值超过1.0,则上限为255(这是过度曝光,更复杂的算法处理这涉及整个图像处理等)。

To get the final 0-255 values for Target you simply multiply all the normalised values back up by 255, making sure you cap at 255 if any of the combined values exceed 1.0 (this is over-exposure and there are more complex algorithms dealing with this that involve whole-image processing etc.).

编辑:在你的问题,你说你想要一个白色背景 - 在这种情况下只是修复BGColor到255,255,255。

In your question you said you want a white background - in that case just fix BGColor to 255,255,255.