如何将颜色对象从解析的 PSD 转换为可用的 RGBA

问题描述 投票:0回答:1

我正在解析 PSD 以获得正常的 RGBA 值,最近我遇到了这个奇怪的浮点颜色值:

{
  "red": 1.0343483686447144,
  "green": 0.9487225413322449,
  "blue": -0.12634865939617157,
  "alpha": 100,
  "rgba": "rgba(1.0343483686447144, 0.9487225413322449, -0.12634865939617157, 1)"
}

这是我的解析函数:

function getRGBColor(color, opacity = 100) {
   if ("Clr " in color) {
      color = color["Clr "];
   }

   var type = color.class.id;
   var red = color["Rd  "];
   var green = color["Grn "];
   var blue = color["Bl  "];

   if ("blueFloat" in color) {
      red = color.redFloat;
      green = color.greenFloat;
      blue = color.blueFloat;
   }

   var rgba = {
      red: red, 
      green: green,
      blue: blue,
      alpha: opacity,
      rgba: `rgba(${red}, ${green}, ${blue}, ${opacity/100})`
   }

   return rgba;
}

应该是黄色的

物体来自

strokeColorContent
.

     var vectorMask = node.get("vectorMask")?.export();
     var vectorStroke = node.get("vectorStroke")?.data;
     var vectorStrokeContent = node.get("vectorStrokeContent")?.data;
     var fillColor = getRGBColor(vectorStrokeContent);

相关问题:
如何将PSD矢量路径转换为SVG路径数据

更新:
我已经按照建议更新了 CSS 以使用

lab()
颜色空间,它似乎有效:

lab(94 -12 103)

我还没有确认 alpha 值,但这似乎有效:

lab(94 -12 103 / 1)  

在大多数浏览器中,似乎都支持

lab()
(目前不在Firefox中,但在Firefox 113中)。

要获得 rgba() 值,需要有一个从 lab 到 rgba 的公式。

html css psd psd.js
1个回答
0
投票

很明显,psd.js 颜色输出对象混淆了 RGB 和 LAB 值。

不幸的是,您只能将 LAB 转换为更通用的 RGB 近似值。

你不能精确地将 LAB 转换为 RGB(没有目标颜色空间定义)

LAB 颜色系统背后的整个想法是提供一个系统来表示 人眼可区分的所有颜色 作为各种颜色转换的参考颜色空间。

解决方法:通用 RGB 近似:

假设你的psd使用了更通用的RGB颜色配置文件,例如类似于sRGB,你可以使用antimatter15的rgb-lab库

let lab = [94, -12, 103, 1];
let rgba = lab2rgb(lab);

labToRgb.style.backgroundColor = `rgba( ${rgba.join(', ')} )`


/**
 * based on 
 * https://github.com/antimatter15/rgb-lab/blob/master/color.js
 */
function lab2rgb(lab) {
  let y = (lab[0] + 16) / 116,
    x = lab[1] / 500 + y,
    z = y - lab[2] / 200,
    r, g, b;

  x = 0.95047 * ((x * x * x > 0.008856) ? x * x * x : (x - 16 / 116) / 7.787);
  y = 1.00000 * ((y * y * y > 0.008856) ? y * y * y : (y - 16 / 116) / 7.787);
  z = 1.08883 * ((z * z * z > 0.008856) ? z * z * z : (z - 16 / 116) / 7.787);

  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;

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

  return [Math.max(0, Math.min(1, r)) * 255,
    Math.max(0, Math.min(1, g)) * 255,
    Math.max(0, Math.min(1, b)) * 255
  ]
}
.color {
  width: 200px;
  height: 200px;
  border: 1px solid #ccc;
}

#rgb {
  background: rgb(255, 242, 0)
}
<div class="color" id="rgb"></div>
<div class="color" id="labToRgb"></div>

理想情况下,您可以解析“输出意图”(目标)颜色配置文件

例如 .icc 文件,然后转换 LAB 颜色以满足所需的目标颜色空间。

© www.soinside.com 2019 - 2024. All rights reserved.