将CSS的Lch值转换为RGB

4

我想将 CSS Lch 颜色字符串转换为:

--my-color: lch(20% 8.5 220.0);

转换为RGB十六进制代码。我尝试使用像Chroma的Lch解析器这样的工具,但它们似乎都使用第一坐标的绝对值(在我的情况中为20%)。

有没有一些标准的方法可以将那20%转换为大多数Lch转换工具使用的亮度值?


首先查看 https://www.w3.org/TR/css-color-4/#lch-to-lab 然后查看 https://www.w3.org/TR/css-color-4/#lab-to-rgb - Kaiido
如果您有不同的范围,可以进行缩放。顺便说一句,“大多数人使用...”并不是一个好问题。我们不知道您考虑了哪些工具(以及您的领域)。您应该始终在问题中指定范围和颜色空间(但请记得在代码中也写下它,否则下次查找错误和定义将需要大量时间)。 - Giacomo Catenazzi
3个回答

2
w3c正在起草一个草案,并附有javascript示例代码(代码太长了,无法在此处发布,而且你需要一些高等数学知识来理解它(至少要涉及sin和2.4的次方)。

2

JS原生的CanvasRenderingContext2D实例可以读取任何以CSS格式(字符串形式)表示的颜色,并将其写入RGBA缓冲区(0到255):

const myCssColor  = "lch(20% 8.5 220.0)";

function cssColor_to_rgba255Color(string) {
    const canvas = document.createElement("canvas");
    canvas.width = canvas.height = 1;
    const ctx = canvas.getContext("2d", {willReadFrequently: true});
    ctx.fillStyle = string;
    ctx.fillRect(0, 0, 1, 1);
    return ctx.getImageData(0, 0, 1, 1).data;
}

const rgba = cssColor_to_rgba255Color(myCssColor);

console.log( rgba[0], rgba[1], rgba[2], rgba[3] );
// 33 51 56 255

这个函数可能性能较差,但可以通过始终回收(使用clearRect)相同的“ctx”对象来进行大幅优化。


1
至少我们确定它使用浏览器的(LCH)实现,并且不需要进行任何数学计算。 - Alexandre Huat

1

我可以给你这个我自己写的从LCH到HEX或RGB的函数。我用PHP编写的,所以很容易适应任何其他语言。

function lch2hex($l, $c, $h) {
  $a=round($c*cos(deg2rad($h)));
  $b=round($c*sin(deg2rad($h)));
  unset($c,$h);
  
  // Reference white values for D65 Light Europe Observer
  // $xw = 0.95047;
  // $yw = 1.00000;
  // $zw = 1.08883;
  
  // Reference white values for CIE 1964 10° Standard Observer
  $xw = 0.948110;
  $yw = 1.00000;
  $zw = 1.07304;
  
  // Compute intermediate values
  $fy = ($l + 16) / 116;
  $fx = $fy + ($a / 500);
  $fz = $fy - ($b / 200);
  
  // Compute XYZ values
  $x = round($xw * (($fx ** 3 > 0.008856) ? $fx ** 3 : (($fx - 16 / 116) / 7.787)),5);
  $y = round($yw * (($fy ** 3 > 0.008856) ? $fy ** 3 : (($fy - 16 / 116) / 7.787)),5);
  $z = round($zw * (($fz ** 3 > 0.008856) ? $fz ** 3 : (($fz - 16 / 116) / 7.787)),5);
  unset($l,$a,$b,$xw,$yw,$zw,$fy,$fx,$fz);
  
  $r = $x * 3.2406 - $y * 1.5372 - $z * 0.4986;
  $g = -$x * 0.9689 + $y * 1.8758 + $z * 0.0415;
  $b = $x * 0.0557 - $y * 0.2040 + $z * 1.0570;
  unset($x,$y,$z);

  $r = $r > 0.0031308 ? 1.055 * pow($r, 1 / 2.4) - 0.055 : 12.92 * $r;
  $g = $g > 0.0031308 ? 1.055 * pow($g, 1 / 2.4) - 0.055 : 12.92 * $g;
  $b = $b > 0.0031308 ? 1.055 * pow($b, 1 / 2.4) - 0.055 : 12.92 * $b;

  $r = round(max(min($r, 1), 0) * 255);
  $g = round(max(min($g, 1), 0) * 255);
  $b = round(max(min($b, 1), 0) * 255);
  
  return '#' . sprintf('%02X%02X%02X', $r, $g, $b);
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接