RGB转十六进制和十六进制转RGB

809

如何将RGB格式的颜色转换为十六进制格式,或将十六进制格式的颜色转换为RGB格式?

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


这里有RGB<->Hex转换,2个十六进制颜色的平均值和随机十六进制颜色的函数。 - ashleedawg
61个回答

1
虽然这个答案不太可能完全符合问题,但它仍然可能非常有用。
1. 创建任何随机元素 ``` var toRgb = document.createElement('div'); ```
2. 将所需颜色设置为任何有效的样式 ``` toRg.style.color = "hsl(120, 60%, 70%)"; ```
3. 再次调用样式属性 ``` > toRgb.style.color; < "rgb(133, 225, 133)" ``` 您的颜色已转换为 Rgb
适用于: Hsl、Hex
不适用于: 命名颜色

当在浏览器中工作时,这可能是最实用的答案。您通常只想将某些现有元素的颜色与以#符号表示的某些已知颜色进行比较。 - Panu Logic

1
基本上,十六进制转RGB:
var hex = '0080C0'.match(/.{1,2}/g).map(e=>parseInt(e, 16));

如果你想要字符串
var rgb = `rgb(${hex.join(", ")})`

RGB转换为十六进制:
var rgb_arr = [0, 128, 40];
var rgb = "#" + rgb_arr.map(e=>e.toString(16).padStart(2, 0)).join("")

0
function getRGB(color){
  if(color.length == 7){
    var r = parseInt(color.substr(1,2),16);
    var g = parseInt(color.substr(3,2),16);
    var b = parseInt(color.substr(5,2),16);    
    return 'rgb('+r+','+g+','+b+')' ;
  }    
  else
    console.log('Enter correct value');
}
var a = getRGB('#f0f0f0');
if(!a){
 a = 'Enter correct value'; 
}

a;

0

基于@MichałPerłakowski的答案(EcmaScipt 6)和他的答案基于Tim Down的答案

我编写了一个修改版的hexToRGB转换函数,增加了安全检查,以确保r/g/b颜色分量在0-255之间,并且该函数可以接受数字r/g/b参数或字符串r/g/b参数,代码如下:

 function rgbToHex(r, g, b) {
     r = Math.abs(r);
     g = Math.abs(g);
     b = Math.abs(b);

     if ( r < 0 ) r = 0;
     if ( g < 0 ) g = 0;
     if ( b < 0 ) b = 0;

     if ( r > 255 ) r = 255;
     if ( g > 255 ) g = 255;
     if ( b > 255 ) b = 255;

    return '#' + [r, g, b].map(x => {
      const hex = x.toString(16);
      return hex.length === 1 ? '0' + hex : hex
    }).join('');
  }

为了安全使用该函数,您应该检查传递的字符串是否是真正的RGB字符串颜色 - 例如,非常简单的检查可以是:

if( rgbStr.substring(0,3) === 'rgb' ) {

  let rgbColors = JSON.parse(rgbStr.replace('rgb(', '[').replace(')', ']'))
  rgbStr = this.rgbToHex(rgbColors[0], rgbColors[1], rgbColors[2]);

  .....
}

这不是 hexToRGB 的修改版本,而是 rgbToHex 的修改版本。 - zenw0lf

0

我找到了这个代码,因为我认为它非常直观,并且拥有验证测试和支持 Alpha 值(可选),这很适合当前情况。

如果你知道自己在做什么并且想要稍微提高一点速度,可以将正则表达式那行代码注释掉。

function hexToRGBA(hex, alpha){
    hex = (""+hex).trim().replace(/#/g,""); //trim and remove any leading # if there (supports number values as well)
    if (!/^(?:[0-9a-fA-F]{3}){1,2}$/.test(hex)) throw ("not a valid hex string"); //Regex Validator
    if (hex.length==3){hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]} //support short form
    var b_int = parseInt(hex, 16);
    return "rgba("+[
        (b_int >> 16) & 255, //R
        (b_int >> 8) & 255, //G
        b_int & 255, //B
        alpha || 1  //add alpha if is set
    ].join(",")+")";
}

0

HTML 转换器 :)

<!DOCTYPE html>
<html>
<body>

<p id="res"></p>

<script>
function hexToRgb(hex) {
  var res = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return "(" + parseInt(res[1], 16) + "," + parseInt(res[2], 16) + "," + parseInt(res[3], 16) + ")";
};

document.getElementById("res").innerHTML = hexToRgb('#0080C0');
</script>

</body>
</html>

0

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

0

看起来你正在寻找这样的东西:

function hexstr(number) {
    var chars = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
    var low = number & 0xf;
    var high = (number >> 4) & 0xf;
    return "" + chars[high] + chars[low];
}

function rgb2hex(r, g, b) {
    return "#" + hexstr(r) + hexstr(g) + hexstr(b);
}

var chars = "0123456789abcdef"; 更容易。 - MrHIDEn

0

我正在处理XAML数据,其十六进制格式为#AARRGGBB(Alpha,Red,Green,Blue)。根据上面的答案,这是我的解决方案:

function hexToRgba(hex) {
    var bigint, r, g, b, a;
    //Remove # character
    var re = /^#?/;
    var aRgb = hex.replace(re, '');
    bigint = parseInt(aRgb, 16);

    //If in #FFF format
    if (aRgb.length == 3) {
        r = (bigint >> 4) & 255;
        g = (bigint >> 2) & 255;
        b = bigint & 255;
        return "rgba(" + r + "," + g + "," + b + ",1)";
    }

    //If in #RRGGBB format
    if (aRgb.length >= 6) {
        r = (bigint >> 16) & 255;
        g = (bigint >> 8) & 255;
        b = bigint & 255;
        var rgb = r + "," + g + "," + b;

        //If in #AARRBBGG format
        if (aRgb.length == 8) {
            a = ((bigint >> 24) & 255) / 255;
            return "rgba(" + rgb + "," + a.toFixed(1) + ")";
        }
    }
    return "rgba(" + rgb + ",1)";
}

http://jsfiddle.net/kvLyscs3/


0

如果要直接从jQuery进行转换,您可以尝试:

  function rgbToHex(color) {
    var bg = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
      return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return     "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
  }

  rgbToHex($('.col-tab-bar .col-tab span').css('color'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接