gpt4 book ai didi

algorithm - HSL 到 RGB 颜色转换

转载 作者:行者123 更新时间:2023-12-03 04:19:07 25 4
gpt4 key购买 nike

我正在寻找一种在 HSL 颜色与 RGB 之间转换的算法。

在我看来,HSL 的使用并不是很广泛,因此我在寻找转换器方面运气不佳。

最佳答案

Garry Tan 在 his blog 上发布了 JavaScript 解决方案(他将其归因于现已不复存在的 mjijackson.com、but is archived herethe original author has a gist - 感谢 user2441511)。

代码重新发布如下(针对 ES5 后的约定进行更新):

HSL 到 RGB:

const { abs, min, max, round } = Math;

/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from https://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param {number} h The hue
* @param {number} s The saturation
* @param {number} l The lightness
* @return {Array} The RGB representation
*/
function hslToRgb(h, s, l) {
let r, g, b;

if (s === 0) {
r = g = b = l; // achromatic
} else {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = hueToRgb(p, q, h + 1/3);
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - 1/3);
}

return [round(r * 255), round(g * 255), round(b * 255)];
}

function hueToRgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}

##RGB 到 HSL:

/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and l in the set [0, 1].
*
* @param {number} r The red color value
* @param {number} g The green color value
* @param {number} b The blue color value
* @return {Array} The HSL representation
*/
function rgbToHsl(r, g, b) {
(r /= 255), (g /= 255), (b /= 255);
const vmax = max(r, g, b), vmin = min(r, g, b);
let h, s, l = (vmax + vmin) / 2;

if (vmax === vmin) {
return [0, 0, l]; // achromatic
}

const d = vmax - vmin;
s = l > 0.5 ? d / (2 - vmax - vmin) : d / (vmax + vmin);
if (vmax === r) h = (g - b) / d + (g < b ? 6 : 0);
if (vmax === g) h = (b - r) / d + 2;
if (vmax === b) h = (r - g) / d + 4;
h /= 6;

return [h, s, l];
}

关于algorithm - HSL 到 RGB 颜色转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2353211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com