-1

I have a color information in decimal values + alpha:

alpha="0.25490198" blue="1.0" green="1.0" red="0.2"
alpha="1.0" blue="0.20392157" green="0.6" red="0.0"
alpha="1.0" blue="0.101960786" green="0.7490196" red="0.3019608"

How can I convert this in HEX for HTML?

Gerd
  • 1,673
  • 19
  • 37
  • 1
    Does this answer your question? [convert Hsl to rgb and hex](https://stackoverflow.com/questions/36721830/convert-hsl-to-rgb-and-hex) – evolutionxbox Jun 22 '21 at 16:24
  • 3
    Why? Just use `rgba(r*255,g*255,b*255,a)` instead – Nick stands with Ukraine Jun 22 '21 at 16:25
  • I got this values form an extern company and no more information. And I'm new in this color questions. I googled and found a lot but nothing about decimal color values + alpha. Sorry! – Gerd Jun 22 '21 at 16:31

1 Answers1

1

Since the alpha channel in your rgba() notation is expressed as a 0 ~ 1 value, you need to multiply it by 255 before trying to convert it to its HEX form:

var colorcode = "rgba(0, 0, 0, 0.74)";

var finalCode = rgba2hex(colorcode)

function rgba2hex(orig) {
  var a, isPercent,
    rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
    alpha = (rgb && rgb[4] || "").trim(),
    hex = rgb ?
    (rgb[1] | 1 << 8).toString(16).slice(1) +
    (rgb[2] | 1 << 8).toString(16).slice(1) +
    (rgb[3] | 1 << 8).toString(16).slice(1) : orig;

  if (alpha !== "") {
    a = alpha;
  } else {
    a = 01;
  }
  // multiply before convert to HEX
  a = ((a * 255) | 1 << 8).toString(16).slice(1)
  hex = hex + a;

  return hex;
}

function test(colorcode) {
  console.log(colorcode, rgba2hex(colorcode));
}

test("rgba(0, 0, 0, 0.74)");
test("rgba(0, 0, 0, 1)");
test("rgba(0, 0, 0, 0)");
test("rgba(0, 255, 0, 0.5)");

But note that this is just one of the rgba notation, and that it will e.g fail with percent based notation. Note also that all browsers do not support RGBA HEX notation, so you might prefer an other method to convert your values depending on what you want to do with it

Example:

alpha="0.25490198" blue="1.0" green="1.0" red="0.2"

alpha=65 blue= 1.0*255 = 255 green= 1.0*255 = 255 red= 0.2*255 = 51  

rgba(51, 255, 255, 0.25490198) = #33FFFF
Gerd
  • 1,673
  • 19
  • 37
Abhishek Chhabra
  • 366
  • 2
  • 12