如何将颜色在RGB格式转换为十六进制格式,反之亦然?

例如,将'#0080C0'转换为(0,128,192)。


当前回答

不可变和人类可理解的版本,没有任何位魔法:

循环数组 使用Math.min()和Math.max()对值< 0或值> 255进行归一化 使用String.toString()将数字转换为十六进制符号 将前导零和修饰值附加到两个字符 将映射值连接到字符串

function rgbToHex(r, g, b) {
  return [r, g, b]
    .map(color => {
      const normalizedColor = Math.max(0, Math.min(255, color));
      const hexColor = normalizedColor.toString(16);

      return `0${hexColor}`.slice(-2);
    })
    .join("");
}

是的,它不会像位操作符那样性能好,但更可读和不可变,所以它不会修改任何输入

其他回答

Tim Down给出的最高评级的答案提供了我所能看到的转换为RGB的最佳解决方案。我更喜欢这个十六进制转换的解决方案,因为它为转换到十六进制提供了最简洁的边界检查和零填充。

function RGBtoHex (red, green, blue) {
  red = Math.max(0, Math.min(~~red, 255));
  green = Math.max(0, Math.min(~~green, 255));
  blue = Math.max(0, Math.min(~~blue, 255));

  return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6);
};

左移'<<'和或'|'操作符的使用也使这成为一个有趣的解决方案。

我假设您指的是html风格的十六进制符号,即#rrggbb。你的代码几乎是正确的,只是顺序颠倒了。它应该是:

var decColor = red * 65536 + green * 256 + blue;

此外,使用位移位可能会让它更容易阅读:

var decColor = (red << 16) + (green << 8) + blue;

上面的一个干净的咖啡脚本版本(谢谢@TimDown):

rgbToHex = (rgb) ->
    a = rgb.match /\d+/g
    rgb  unless a.length is 3
    "##{ ((1 << 24) + (parseInt(a[0]) << 16) + (parseInt(a[1]) << 8) + parseInt(a[2])).toString(16).slice(1) }"
function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}

以下是我的看法:

function rgbToHex(red, green, blue) {
  const rgb = (red << 16) | (green << 8) | (blue << 0);
  return '#' + (0x1000000 + rgb).toString(16).slice(1);
}

function hexToRgb(hex) {
  const normal = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
  if (normal) return normal.slice(1).map(e => parseInt(e, 16));

  const shorthand = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
  if (shorthand) return shorthand.slice(1).map(e => 0x11 * parseInt(e, 16));

  return null;
}