YoshiJaeger
YoshiJaeger

Reputation: 1210

Subtraction of colours - Need to get the transparent value of a colour

I was just trying to get the rgba value of a rgb-colour (#ebfcff). The rgb-colour is the rgba when put on a white background. (a stands for alpha)

So: searchedColour + #ffffff = #ebfcff

In my assessment the solution would be to subtract white from #ebfcff. But how do you subtract colours ?

I already searched for an adequate solution. Does anyone know how to subtract white from a given RGB-Colour to get a new colour, which is in rgba-format, that equals the given colour when it gets overlapped with white ?

Upvotes: 1

Views: 2994

Answers (1)

John B. Lambe
John B. Lambe

Reputation: 557

Colour values aren't just added.

When you plot a colour X on top of a colour Y, the value of each colour channel of the resulting colour, C, is given by:

C = X * a + Y * (1-a)

using the floating point representation (each channel is a value from 0 to 1); where a is the alpha channel of X. (It's easily converted back to 0-255).

On a white background, Y is 1 for all channels, so:

C = X * a + (1-a)

So, if a is 0, you clearly can't find X, which makes sense: If the colour was totally transparent, it makes no difference to the combined colour.

Similarly, if your colour was white (X=1) (on a white background), you couldn't determine the alpha (the combined colour would be white regardless of the alpha).

Also, you can't find either X or a without knowing the other.

If you knew the alpha of the colour (a), then you could determine what the colour (X) was, but if your combined colour (C) is a discrete value (such as an integer from 0 to 255), then it is rounded, so you can only get an approximation of the plotted colour (X). How accurate it is depends on the alpha (the more transparent the plotted colour was, the less accurately you can determine the colour).

So, solving for X (where the background (Y) is white):

            X * a = C + a - 1
Therefore:  X = (C + a - 1 ) / a

For 8-bit colour channels (24-bit colour):

X = 255 * ( C/255 + a/255 - 1 ) / (a/255)

(Given a 6-digit hexadecimal value, apply this for each pair of digits, C).

You could optimise it to avoid the floating point calculation.

I don't know if that's any use, but that's all you can do.

Upvotes: 4

Related Questions