Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programatically calculate base colour required to achieve a specific colour after applying a translucent overlay

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"

like image 796
Scoots Avatar asked Oct 28 '25 10:10

Scoots


1 Answers

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.

like image 52
Haroldo_OK Avatar answered Oct 29 '25 23:10

Haroldo_OK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!