如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
当前回答
我建议使用一个经过良好测试和维护的库:Colors.js(可用于node.js和浏览器),而不是复制和粘贴到处都能找到的代码片段。它只有7 KB(压缩后更少)。
其他回答
不可变和人类可理解的版本,没有任何位魔法:
循环数组 使用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("");
}
是的,它不会像位操作符那样性能好,但更可读和不可变,所以它不会修改任何输入
上面的一个干净的咖啡脚本版本(谢谢@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) }"
注意:rgbToHex的两个版本都期望r, g和b为整数值,所以如果你有非整数值,你需要自己做四舍五入。
下面将做RGB到十六进制的转换,并添加任何所需的零填充:
函数componentToHex(c) { var hex = c.toString(16); 返回十六进制。长度== 1 ?“0”+ hex: hex; } 函数rgbToHex(r, g, b) { 返回“#”+ componentToHex(r) + componentToHex(g) + componentToHex(b); } alert(rgbToHex(0, 51,255));/ / # 0033 ff
另一种转换方式:
函数hexToRgb(hex) { var结果= / ^ # ? (f \ d {2}) (f \ d {2}) (f \ d{2}) /美元i.exec(十六进制); 返回结果?{ r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) }: null; } 警报(hexToRgb (# 0033 ff) .g);/ /“51”;
最后,rgbToHex()的另一个版本,正如@casablanca的回答中所讨论的,并在@cwolves的评论中建议:
函数rgbToHex(r, g, b) { 返回“#”+ (1 < < 24 | r < < 16 g | < < 8 | b) .toString (16) .slice (1); } alert(rgbToHex(0, 51,255));/ / # 0033 ff
2012年12月3日更新
下面是hexToRgb()的一个版本,它也可以解析一个简化的十六进制三元组,例如“#03F”:
function hexToRgb(hex) { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } alert(hexToRgb("#0033ff").g); // "51"; alert(hexToRgb("#03f").g); // "51";
HEX转RGB (ES6) +测试[2022]
convertHexToRgb.ts:
/**
* RGB color regexp
*/
export const RGB_REG_EXP = /rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/;
/**
* HEX color regexp
*/
export const HEX_REG_EXP = /^#?(([\da-f]){3}|([\da-f]){6})$/i;
/**
* Converts HEX to RGB.
*
* Color must be only HEX string and must be:
* - 7-characters starts with "#" symbol ('#ffffff')
* - or 6-characters without "#" symbol ('ffffff')
* - or 4-characters starts with "#" symbol ('#fff')
* - or 3-characters without "#" symbol ('fff')
*
* @function { color: string => string } convertHexToRgb
* @return { string } returns RGB color string or empty string
*/
export const convertHexToRgb = (color: string): string => {
const errMessage = `
Something went wrong while working with colors...
Make sure the colors provided to the "PieDonutChart" meet the following requirements:
Color must be only HEX string and must be
7-characters starts with "#" symbol ('#ffffff')
or 6-characters without "#" symbol ('ffffff')
or 4-characters starts with "#" symbol ('#fff')
or 3-characters without "#" symbol ('fff')
- - - - - - - - -
Error in: "convertHexToRgb" function
Received value: ${color}
`;
if (
!color
|| typeof color !== 'string'
|| color.length < 3
|| color.length > 7
) {
console.error(errMessage);
return '';
}
const replacer = (...args: string[]) => {
const [
_,
r,
g,
b,
] = args;
return '' + r + r + g + g + b + b;
};
const rgbHexArr = color
?.replace(HEX_REG_EXP, replacer)
.match(/.{2}/g)
?.map(x => parseInt(x, 16));
/**
* "HEX_REG_EXP.test" is here to create more strong tests
*/
if (rgbHexArr && Array.isArray(rgbHexArr) && HEX_REG_EXP.test(color)) {
return `rgb(${rgbHexArr[0]}, ${rgbHexArr[1]}, ${rgbHexArr[2]})`;
}
console.error(errMessage);
return '';
};
我正在使用Jest进行测试
color.spec.ts
describe('function "convertHexToRgb"', () => {
it('returns a valid RGB with the provided 3-digit HEX color: [color = \'fff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('fff');
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns a valid RGB with the provided 3-digit HEX color with hash symbol: [color = \'#fff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('#fff');
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns a valid RGB with the provided 6-digit HEX color: [color = \'ffffff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('ffffff');
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns a valid RGB with the provided 6-digit HEX color with the hash symbol: [color = \'#ffffff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb(TEST_COLOR);
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns an empty string when the provided value is not a string: [color = 1234]', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
// @ts-ignore
const rgb = convertHexToRgb(1234);
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided color is too short: [color = \'FF\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('FF');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided color is too long: [color = \'#fffffff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('#fffffff');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided value is looks like HEX color string but has invalid symbols: [color = \'#fffffp\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('#fffffp');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided value is invalid: [color = \'*\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('*');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided value is undefined: [color = undefined]', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
// @ts-ignore
const rgb = convertHexToRgb(undefined);
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
});
测试结果:
function "convertHexToRgb"
√ returns a valid RGB with the provided 3-digit HEX color: [color = 'fff']
√ returns a valid RGB with the provided 3-digit HEX color with hash symbol: [color = '#fff']
√ returns a valid RGB with the provided 6-digit HEX color: [color = 'ffffff']
√ returns a valid RGB with the provided 6-digit HEX color with the hash symbol: [color = '#ffffff']
√ returns an empty string when the provided value is not a string: [color = 1234]
√ returns an empty string when the provided color is too short: [color = 'FF']
√ returns an empty string when the provided color is too long: [color = '#fffffff']
√ returns an empty string when the provided value is looks like HEX color string but has invalid symbols: [color = '#fffffp']
√ returns an empty string when the provided value is invalid: [color = '*']
√ returns an empty string when the provided value is undefined: [color = undefined]
和mockConsole:
export const mockConsole = () => {
const consoleError = jest.spyOn(console, 'error').mockImplementationOnce(() => undefined);
return { consoleError };
};
这可以用于从计算样式属性中获取颜色:
function rgbToHex(color) {
color = ""+ color;
if (!color || color.indexOf("rgb") < 0) {
return;
}
if (color.charAt(0) == "#") {
return color;
}
var nums = /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(color),
r = parseInt(nums[2], 10).toString(16),
g = parseInt(nums[3], 10).toString(16),
b = parseInt(nums[4], 10).toString(16);
return "#"+ (
(r.length == 1 ? "0"+ r : r) +
(g.length == 1 ? "0"+ g : g) +
(b.length == 1 ? "0"+ b : b)
);
}
// not computed
<div style="color: #4d93bc; border: 1px solid red;">...</div>
// computed
<div style="color: rgb(77, 147, 188); border: 1px solid rgb(255, 0, 0);">...</div>
console.log( rgbToHex(color) ) // #4d93bc
console.log( rgbToHex(borderTopColor) ) // #ff0000
裁判:https://github.com/k-gun/so/blob/master/so_util.js