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

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


当前回答

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

其他回答

CSS Level 4边注:一般来说,你想要能够将十六进制转换为RGB的原因是alpha通道,在这种情况下,你可以很快用CSS4添加一个十六进制。例如:#FF8800FF或#f80f表示全透明的橙色。

除此之外,下面的代码在一个函数中回答了这两个问题,从另一个函数到另一个函数。这接受一个可选的alpha通道,支持字符串数组格式,解析3,4,6,7个字符的十六进制,和rgb/a完整或部分字符串(百分比定义的rgb/a值除外)没有标志。

(如果支持IE,替换少量的ES6语法)

一句话:

function rgbaHex(c,a,i){return(Array.isArray(c)||(typeof c==='string'&&/,/.test(c)))?((c=(Array.isArray(c)?c:c.replace(/[\sa-z\(\);]+/gi,'').split(',')).map(s=>parseInt(s).toString(16).replace(/^([a-z\d])$/i,'0$1'))),'#'+c[0]+c[1]+c[2]):(c=c.replace(/#/,''),c=c.length%6?c.replace(/(.)(.)(.)/,'$1$1$2$2$3$3'):c,a=parseFloat(a)||null,`rgb${a?'a':''}(${[(i=parseInt(c,16))>>16&255,i>>8&255,i&255,a].join().replace(/,$/,'')})`);}

可读版本:

function rgbaHex(c, a) {
    // RGBA to Hex
    if (Array.isArray(c) || (typeof c === 'string' && /,/.test(c))) {
        c = Array.isArray(c) ? c : c.replace(/[\sa-z\(\);]+/gi, '').split(',');
        c = c.map(s => window.parseInt(s).toString(16).replace(/^([a-z\d])$/i, '0$1'));

        return '#' + c[0] + c[1] + c[2];
    }
    // Hex to RGBA
    else {
        c = c.replace(/#/, '');
        c = c.length % 6 ? c.replace(/(.)(.)(.)/, '$1$1$2$2$3$3') : c;
        c = window.parseInt(c, 16);

        a = window.parseFloat(a) || null;

        const r = (c >> 16) & 255;
        const g = (c >> 08) & 255;
        const b = (c >> 00) & 255;

        return `rgb${a ? 'a' : ''}(${[r, g, b, a].join().replace(/,$/,'')})`;
    }
}

Usages:

rgbaHex(“# a8f”)

rgbaHex(“# aa88ff”)

rgbaHex(“# A8F”)

rgbaHex(“# AA88FF”)

rgbaHex('#AA88FF', 0.5)

rgbaHex(“# a8f”、“0.85”)

/ /等。

rgbaHex('rgba(170,136,255,0.8);')

rgbaHex('rgba(170,136,255,0.8)')

rgbaHex('rgb(170,136,255)')

rgbaHex('rg170,136,255')

rgbaHex(' 170,136,255 ')

rgbaHex 170,136,255,0.8 ([])

rgbaHex ([170136255])

/ /等。

这段代码接受#fff和#ffffff变量和不透明度。

function hex2rgb(hex, opacity) {
        var h=hex.replace('#', '');
        h =  h.match(new RegExp('(.{'+h.length/3+'})', 'g'));

        for(var i=0; i<h.length; i++)
            h[i] = parseInt(h[i].length==1? h[i]+h[i]:h[i], 16);

        if (typeof opacity != 'undefined')  h.push(opacity);

        return 'rgba('+h.join(',')+')';
}

一个简单的答案,将RGB转换为十六进制。这里颜色通道的值被限定在0到255之间。

function RGBToHex(r = 0, g = 0, b = 0) {
    // clamp and convert to hex
    let hr = Math.max(0, Math.min(255, Math.round(r))).toString(16);
    let hg = Math.max(0, Math.min(255, Math.round(g))).toString(16);
    let hb = Math.max(0, Math.min(255, Math.round(b))).toString(16);
    return "#" +
        (hr.length<2?"0":"") + hr +
        (hg.length<2?"0":"") + hg +
        (hb.length<2?"0":"") + hb;
}

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

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