2

I'm trying to combine two RGBA colors, given in tuples, like (0, 0, 0, 128) and (255, 255, 255, 128). I've already found this which was quite helpful, but my current code (Python)

def get_color(colorRGBA1, colorRGBA2):
    alpha = 255 - (255 - colorRGBA1[3]) * (255 - colorRGBA2[3])
    red   = (colorRGBA1[0] * (255 - colorRGBA2[3]) + colorRGBA2[0] * colorRGBA2[3]) / 255
    green = (colorRGBA1[1] * (255 - colorRGBA2[3]) + colorRGBA2[1] * colorRGBA2[3]) / 255
    blue  = (colorRGBA1[2] * (255 - colorRGBA2[3]) + colorRGBA2[2] * colorRGBA2[3]) / 255
    return (int(red), int(green), int(blue), int(alpha))

somehow returns some weird numbers (like -15874) as alpha. Everything else works fine, but I can't figure out how to get the new color's alpha value.

Both colors will have alpha values ranging from 0 to 255.

Community
  • 1
  • 1
charlie
  • 389
  • 3
  • 16

2 Answers2

4

The correct code is:

def get_color(colorRGBA1, colorRGBA2):
    alpha = 255 - ((255 - colorRGBA1[3]) * (255 - colorRGBA2[3]) / 255)
    red   = (colorRGBA1[0] * (255 - colorRGBA2[3]) + colorRGBA2[0] * colorRGBA2[3]) / 255
    green = (colorRGBA1[1] * (255 - colorRGBA2[3]) + colorRGBA2[1] * colorRGBA2[3]) / 255
    blue  = (colorRGBA1[2] * (255 - colorRGBA2[3]) + colorRGBA2[2] * colorRGBA2[3]) / 255
    return (int(red), int(green), int(blue), int(alpha))

...because I have to divide (255 - colorRGBA1[3]) * (255 - colorRGBA2[3]) by 255 to get a valid alpha value.

Jongware
  • 22,200
  • 8
  • 54
  • 100
charlie
  • 389
  • 3
  • 16
1

See solution in JavaScript at https://gist.github.com/JordanDelcros/518396da1c13f75ee057

Please note that this implementation has alpha in [0,1] range, so divide your alpha values by 255 before mixing and at the end multiply the final alpha by 255.

Ωmega
  • 42,614
  • 34
  • 134
  • 203