3

I'm trying to create a tool to help me with choosing colours for web applications. Basically, I want to be able to specify a final colour and some overlay parameters and determine what the underlying colour needs to be (or if it's possible to achieve with the specified parameters).

All overlays will be translucent black.

An example of how the system would work:

  1. I enter the following variables:
    • finalColourRed: 128 [0-255]
    • finalColourGreen: 118 [0-255]
    • finalColourBlue: 107 [0-255]
    • overlayOpacity: 0.21 [0-1]
  2. The system returns:
    • rgb(183, 169, 154)

I should note that I don't need help with writing the actual code for this, I just don't know the mathematical formula to use and my Google-fu is weak today. The closest I could find was this excellent answer (https://stackoverflow.com/a/12228643/4027341) but it's missing an iteration for "knowing final desired colour, knowing overlay colour, knowing overlay opacity"

Scoots
  • 3,048
  • 2
  • 21
  • 33

1 Answers1

4

You can do it one channel at a time; the formula works like that:

The final color for a channel would be computed as:

finalColor = originalColor * (1.0 - opacity) + overlayColor * opacity;

In your case, you know the final color, the overlay color and the opacity; doing some algebra, we arrive at the conclusion that:

originalColor = (finalColor - overlayColor * opacity) / (1.0 - opacity);

Just be aware of the edge case where opacity = 1.0; you simply can't compute the original color in this case; more specifically, if opacity = 1.0, any color will do the job.

Also, the formula may end up producing negative values or values greater than 255; those values mean that you can't quite obtain a color that will give the results you want.

Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80