Pergunta

Given a css color value like:

 rgba(0, 0, 0, 0.86)

How do I convert that to a RGB hex value that takes the alpha component into account, assuming a white background?

Foi útil?

Solução

Since alpha value both attenuates the background color and the color value, something like this could do the trick:

function rgba2rgb(RGB_background, RGBA_color)
{
    var alpha = RGBA_color.a;

    return new Color(
        (1 - alpha) * RGB_background.r + alpha * RGBA_color.r,
        (1 - alpha) * RGB_background.g + alpha * RGBA_color.g,
        (1 - alpha) * RGB_background.b + alpha * RGBA_color.b
    );
}

(Try it interactively: https://marcodiiga.github.io/rgba-to-rgb-conversion)

Outras dicas

Assuming that the values are 0...1 per channel. And assuming that the abbreviation in the method / function call in the question correspond to the arguments, the following should work.

A = 255 * 0.86
R = 255 * 0
G = 255 * 0
B = 255 * 0

Note you may want to change how it rounds off here as it may give inaccuracies in colours.

At this point, the values are in fact still floating point values, but casting them to a byte or a char (depending on language), should in theory work.

var _A = (byte)219.3
var _R = (byte)0
var _G = (byte)0
var _B = (byte)0

Now all you have to do is convert them to a hexadecimal string each, and concatenate them (ARGB) and put a nice little hash tag in front (#)

In C# you could do something akin to:

var hexString = string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", _A, _R, _G, _B);

Yielding a final result of something like:

#DB000000

you can convert red,green and blue individually using .toString(16) and then combine the result in a case, if you just want to convert a rgb to hex... since you are searching to convert rgba to hex i thought it would be better to convert the rgba to rgb and then to hex as i did in the following Fiddle, which would also consider the background-color of the parent div.

The rgba value you are having is: rgba(0, 0, 0, 0.86)

First 0 stands for RED
Second 0 stands for GREEN
Third 0 stands for BLUE
and the last digit 0.86 stands for alpha/opacity

Here are some links for rgb to hex converter:

http://www.javascripter.net/faq/rgbtohex.htm
http://www.rgbtohex.net/
http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php

with you digits 0, 0, 0. The Hex Code will be

#000000

Following is the code for low opacity with a white background

HTML

<div id="parentDiv">
    <div id="childDiv">

    </div>
</div>

CSS

#parentDiv
{
height:100px;  /* The property of Child is Inherit */
width:100px;  /* The property of Child is Inherit*/
background-color:#ffffff;
}

#childDiv
{
height:inherit;
width:inherit;
background-color:#000000;
opacity:0.86;
filter:alpha(opacity="86");
}

Now the parent Div is the background with

#ffffff (White color)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top