RGB to Hex and Hex to RGB

2018-12-31 01:50发布

How to convert colors in RGB format to Hex format and vice versa?

For example, convert '#0080C0' to (0, 128, 192).

30条回答
若你有天会懂
2楼-- · 2018-12-31 02:21

This could be used for getting colors from computed style propeties:

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

Refs:
https://github.com/k-gun/so/blob/master/so_util.js#L10
https://github.com/k-gun/so/blob/master/so_util.js#L62
https://github.com/k-gun/so/blob/master/so_util.js#L81

查看更多
不流泪的眼
3楼-- · 2018-12-31 02:21

i needed a function that accepts invalid values too like

rgb(-255, 255, 255) rgb(510, 255, 255)

this is a spin off of @cwolves answer

function rgb(r, g, b) {
  this.c = this.c || function (n) {
    return Math.max(Math.min(n, 255), 0)
  };

  return ((1 << 24) + (this.c(r) << 16) + (this.c(g) << 8) + this.c(b)).toString(16).slice(1).toUpperCase();
}
查看更多
忆尘夕之涩
4楼-- · 2018-12-31 02:21

I came across this problem since I wanted to accept any color value and be able to add an opacity, so I made this quick jQuery plugin that uses the native canvas on modern browsers. Seems to work just great.

Edit

Turns out I can't figure out how to make it a proper jQuery plugin, so I'll just present it as a regular function.

//accepts any value like '#ffffff', 'rgba(255,255,255,1)', 'hsl(0,100%,100%)', or 'white'
function toRGBA( c ) {
    var
        can  = document.createElement( 'canvas' ),
        ctx  = can.getContext( '2d' );
    can.width = can.height = 1;
    ctx.fillStyle = c;
    console.log( ctx.fillStyle ); //always css 6 digit hex color string, e.g. '#ffffff'
    ctx.fillRect( 0, 0, 1, 1 ); //paint the canvas
    var
        img  = ctx.getImageData( 0, 0, 1, 1 ),
        data = img.data,
        rgba = {
            r: data[ 0 ], //0-255 red
            g: data[ 1 ], //0-255 green
            b: data[ 2 ], //0-255 blue
            a: data[ 3 ]  //0-255 opacity (0 being transparent, 255 being opaque)
        };
    return rgba;
};
查看更多
像晚风撩人
5楼-- · 2018-12-31 02:22

I'm working with XAML data that has a hex format of #AARRGGBB (Alpha, Red, Green, Blue). Using the answers above, here's my solution:

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/

查看更多
刘海飞了
6楼-- · 2018-12-31 02:22

A total different approach to convert hex color code to RGB without regex

It handles both #FFF and #FFFFFF format on the base of length of string. It removes # from beginning of string and divides each character of string and converts it to base10 and add it to respective index on the base of it's position.

//Algorithm of hex to rgb conversion in ES5
function hex2rgbSimple(str){
  str = str.replace('#', '');
  return str.split('').reduce(function(result, char, index, array){
    var j = parseInt(index * 3/array.length);
    var number = parseInt(char, 16);
    result[j] = (array.length == 3? number :  result[j]) * 16 + number;
    return result;
  },[0,0,0]);
}

//Same code in ES6
hex2rgb = str => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]);

//hex to RGBA conversion
hex2rgba = (str, a) => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0,a||1]);

//hex to standard RGB conversion
hex2rgbStandard = str => `RGB(${str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]).join(',')})`;


console.log(hex2rgb('#aebece'));
console.log(hex2rgbSimple('#aebece'));

console.log(hex2rgb('#aabbcc'));

console.log(hex2rgb('#abc'));

console.log(hex2rgba('#abc', 0.7));

console.log(hex2rgbStandard('#abc'));

查看更多
公子世无双
7楼-- · 2018-12-31 02:24
function hexToRgb(str) { 
    if ( /^#([0-9a-f]{3}|[0-9a-f]{6})$/ig.test(str) ) { 
        var hex = str.substr(1);
        hex = hex.length == 3 ? hex.replace(/(.)/g, '$1$1') : hex;
        var rgb = parseInt(hex, 16);               
        return 'rgb(' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join(',') + ')';
    } 

    return false; 
}

function rgbToHex(red, green, blue) {
    var out = '#';

    for (var i = 0; i < 3; ++i) {
        var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);

        if (isNaN(n) || n < 0 || n > 255) {
            return false;
        }

        out += (n < 16 ? '0' : '') + n.toString(16);
    }

    return out
查看更多
登录 后发表回答