如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
当前回答
注意: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总是6个字符,带或不带#前缀,那么如果你想做一些快速内联的东西,这可能是最简单的方法。它不关心是否以散列开始。
var hex = "#ffffff";
var rgb = [
parseInt(hex.substr(-6,2),16),
parseInt(hex.substr(-4,2),16),
parseInt(hex.substr(-2),16)
];
建立了我自己的十六进制RGB转换器。我希望这能帮助到一些人。
我用react来做沙盒。
用法:
根据官方文档安装React,或者如果你全局安装了npx,运行npx create-react-app hexto -rgb
import React, { Component, Fragment } from 'react';
const styles = {
display: 'block',
margin: '20px auto',
input: {
width: 170,
},
button: {
margin: '0 auto'
}
}
// test case 1
// #f0f
// test case 2
// #ff00ff
class HexToRGBColorConverter extends Component {
state = {
result: false,
color: "#ff00ff",
}
hexToRgb = color => {
let container = [[], [], []];
// check for shorthand hax string
if (color.length >= 3) {
// remove hash from string
// convert string to array
color = color.substring(1).split("");
for (let key = 0; key < color.length; key++) {
let value = color[key];
container[2].push(value);
// if the length is 3 we
// we need to add the value
// to the index we just updated
if (color.length === 3) container[2][key] += value;
}
for (let index = 0; index < color.length; index++) {
let isEven = index % 2 === 0;
// If index is odd an number
// push the value into the first
// index in our container
if (isEven) container[0].push(color[index]);
// If index is even an number
if (!isEven) {
// again, push the value into the
// first index in the container
container[0] += color[index];
// Push the containers first index
// into the second index of the container
container[1].push(container[0]);
// Flush the first index of
// of the container
// before starting a new set
container[0] = [];
}
}
// Check container length
if (container.length === 3) {
// Remove only one element of the array
// Starting at the array's first index
container.splice(0, 1);
let values = container[color.length % 2];
return {
r: parseInt(values[0], 16),
g: parseInt(values[1], 16),
b: parseInt(values[2], 16)
}
}
}
return false;
}
handleOnClick = event => {
event.preventDefault();
const { color } = this.state;
const state = Object.assign({}, this.state);
state.result = this.hexToRgb(color);
this.setState(state);
}
handleOnChange = event => {
event.preventDefault();
const { value } = event.currentTarget;
const pattern = /^([a-zA-Z0-9])/;
const boundaries = [3, 6];
if (
pattern.test(value) &&
boundaries.includes(value.length)
) {
const state = Object.assign({}, this.state);
state.color = `#${value}`;
this.setState(state);
}
}
render() {
const { color, result } = this.state;
console.log('this.state ', color, result);
return (
<Fragment>
<input
type="text"
onChange={this.handleOnChange}
style={{ ...styles, ...styles.input }} />
<button
onClick={this.handleOnClick}
style={{ ...styles, ...styles.button }}>
Convert hex to rgba
</button>
{
!!result &&
<div style={{ textAlign: 'center' }}>
Converted { color } to { JSON.stringify(result) }
</div>
}
</Fragment>
)
}
}
export default App;
快乐编码=)
我假设您指的是html风格的十六进制符号,即#rrggbb。你的代码几乎是正确的,只是顺序颠倒了。它应该是:
var decColor = red * 65536 + green * 256 + blue;
此外,使用位移位可能会让它更容易阅读:
var decColor = (red << 16) + (green << 8) + blue;
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 hex2rgb(hex) {
return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}