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

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


当前回答

RGB转十六进制

使用padStart ()

你可以使用padStart()来使用这个在线程序:

RGB = (r, g, b) => { 返回' #${[r, g, b].map((x) => x. tostring(16)。padStart(“0”)). join (" ")} '; }

另外,它在传统浏览器上不受支持,请在这里检查它的兼容性。

没有padStart ()

如果你不想使用padStart(),你可以实现这个函数:

RGB = (r, g, b) => { 返回' #${[r, g, b] . map ((n) = > n.toString(16)。长度=== 1 ?“0”+ n.toString(16): n.toString(16) ) . join (" ")} '; };

参数验证

如果你不确定谁将使用你的函数,你必须使用参数验证,即值是有效的(0到255之间),要做到这一点,在每次返回之前添加这些条件:

If (r > 255) r = 255;if (r < 0) r = 0; If (g > 255) g = 255;if (g < 0) g = 0; If (b > 255) b = 255;如果(b < 0) b = 0;

所以上面两个例子就变成了:

const rgb = (r, g, b) => { if (r > 255) r = 255; else if (r < 0) r = 0; if (g > 255) g = 255; else if (g < 0) g = 0; if (b > 255) b = 255; else if (b < 0) b = 0; return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`; }; const rgb2 = (r, g, b) => { if (r > 255) r = 255; else if (r < 0) r = 0; if (g > 255) g = 255; else if (g < 0) g = 0; if (b > 255) b = 255; else if (b < 0) b = 0; return `#${[r, g, b] .map((n) => n.toString(16).length === 1 ? "0" + n.toString(16) : n.toString(16) ) .join("")}`; };


十六进制到RGB

为此,我们将使用一些RegEx:

Const hex = (h) => { 返回h .replace ( / ^ # ? (\ d] [a - f) (\ d] [a - f) (\ d] [a - f) /我美元, (_, r, g, b) => "#" + r + r + g + g + b + b ) .substring (1) .match (/ {2} / g)。 .map((x) => parseInt(x, 16)); };

其他回答

注意: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";

2021年版

你可以简单地使用rgb-十六进制和十六进制-rgb,因为它是经过战斗测试的,有多个选项,在其他解决方案中是不可用的。

我最近正在构建一个颜色选择器&这2个包派上用场。

使用

rgb-hex

import rgbHex from 'rgb-hex';

rgbHex(65, 131, 196);
//=> '4183c4'

rgbHex('rgb(40, 42, 54)');
//=> '282a36'

rgbHex(65, 131, 196, 0.2);
//=> '4183c433'

rgbHex(40, 42, 54, '75%');
//=> '282a36bf'

rgbHex('rgba(40, 42, 54, 75%)');
//=> '282a36bf'

hex-rgb

import hexRgb from 'hex-rgb';

hexRgb('4183c4');
//=> {red: 65, green: 131, blue: 196, alpha: 1}

hexRgb('#4183c4');
//=> {red: 65, green: 131, blue: 196, alpha: 1}

hexRgb('#fff');
//=> {red: 255, green: 255, blue: 255, alpha: 1}

hexRgb('#22222299');
//=> {red: 34, green: 34, blue: 34, alpha: 0.6}

hexRgb('#0006');
//=> {red: 0, green: 0, blue: 0, alpha: 0.4}

hexRgb('#cd2222cc');
//=> {red: 205, green: 34, blue: 34, alpha: 0.8}

hexRgb('#cd2222cc', {format: 'array'});
//=> [205, 34, 34, 0.8]

hexRgb('#cd2222cc', {format: 'css'});
//=> 'rgb(205 34 34 / 80%)'

hexRgb('#000', {format: 'css'});
//=> 'rgb(0 0 0)'

hexRgb('#22222299', {alpha: 1});
//=> {red: 34, green: 34, blue: 34, alpha: 1}

hexRgb('#fff', {alpha: 0.5});
//=> {red: 255, green: 255, blue: 255, alpha: 0.5}

我意识到这个问题有很多答案,但如果你像我一样,你知道你的HEX总是6个字符,带或不带#前缀,那么如果你想做一些快速内联的东西,这可能是最简单的方法。它不关心是否以散列开始。

var hex = "#ffffff";
var rgb = [
    parseInt(hex.substr(-6,2),16),
    parseInt(hex.substr(-4,2),16),
    parseInt(hex.substr(-2),16)
];

从HEX转换为RGB,其中RGB是0到1范围内的浮点值:

#FFAA22→{r: 0.5, g: 0, b:1}

我改编了@Tim Down的回答:


function convertRange(value,oldMin,oldMax,newMin,newMax) {
  return (Math.round(((((value - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin) * 10000)/10000)
}

function hexToRgbFloat(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: convertRange(parseInt(result[1],16), 0, 255, 0, 1),
    g: convertRange(parseInt(result[2],16), 0, 255, 0, 1),
    b: convertRange(parseInt(result[3],16), 0, 255, 0, 1)
  } : null;
}

console.log(hexToRgbFloat("#FFAA22")) // {r: 1, g: 0.6667, b: 0.1333}

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 };
};