# 十六进制颜色转 RGB

> 把 #FF8800、#FF880080 这类十六进制颜色转为 rgb() 或 rgba()，其余文字不变

版本：1.0.0 · 作者 Deck

- 安装到 Deck：deck://install-plugin?id=hex-to-rgb&url=https%3A%2F%2Fgithub.com%2Fyuzeguitarist%2Fdeck-plugins%2Freleases%2Fdownload%2Fplugins%2Fhex-to-rgb-1.0.0.zip
- 下载 .zip：https://github.com/yuzeguitarist/deck-plugins/releases/download/plugins/hex-to-rgb-1.0.0.zip
- 在 GitHub 上查看：https://github.com/yuzeguitarist/deck-plugins/tree/main/plugins/hex-to-rgb

也可以用终端安装：

```sh
mkdir -p ~/.deck/scripts/hex-to-rgb && curl -fsSL https://github.com/yuzeguitarist/deck-plugins/releases/download/plugins/hex-to-rgb-1.0.0.zip | tar -xf - -C ~/.deck/scripts/hex-to-rgb
```

## 脚本

```js
// Turns hex colors (#RGB, #RGBA, #RRGGBB and #RRGGBBAA) into rgb() or rgba() and leaves the rest of the text as it is.
const HEX_COLOR = /(^|[^\w&\/])#([0-9A-Fa-f]{8}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{3,4})(?!\w)/g;

// Alpha with two decimals, or three when two do not map back to the same byte, as browsers print it.
function alpha(byte) {
  const two = Math.round((byte / 255) * 100) / 100;
  return String(Math.round(two * 255) === byte ? two : Math.round((byte / 255) * 1000) / 1000);
}

function transform(input) {
  return String(input ?? "").replace(HEX_COLOR, (color, before, hex) => {
    const digits = hex.length <= 4 ? hex.replace(/./g, "$&$&") : hex;
    const channel = (k) => parseInt(digits.slice(k * 2, k * 2 + 2), 16);
    const rgb = channel(0) + ", " + channel(1) + ", " + channel(2);
    return before + (digits.length === 6 ? "rgb(" + rgb + ")" : "rgba(" + rgb + ", " + alpha(channel(3)) + ")");
  });
}
```

---

- HTML：https://deckclip.app/zh-cn/plugins/hex-to-rgb
- English：https://deckclip.app/plugins/hex-to-rgb.md

© 2026 潘禹泽
