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:32

One-line functional HEX to RGBA

Supports both short #fff and long #ffffff forms.
Supports alpha channel (opacity).
Does not care if hash specified or not, works in both cases.

function hexToRGBA(hex, opacity) {
    return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(opacity||1).join(',') + ')';
}

examples:

hexToRGBA('#fff')        ->  rgba(255,255,255,1)  
hexToRGBA('#ffffff')     ->  rgba(255,255,255,1)  
hexToRGBA('#fff', .2)    ->  rgba(255,255,255,0.2)  
hexToRGBA('#ffffff', .2) ->  rgba(255,255,255,0.2)  
hexToRGBA('fff', .2)     ->  rgba(255,255,255,0.2)  
hexToRGBA('ffffff', .2)  ->  rgba(255,255,255,0.2)  
查看更多
低头抚发
3楼-- · 2018-12-31 02:32

I found this and because I think it is pretty straight forward and has validation tests and supports alpha values (optional), this will fit the case.

Just comment out the regex line if you know what you're doing and it's a tiny bit faster.

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(",")+")";
}
查看更多
长期被迫恋爱
4楼-- · 2018-12-31 02:35

My version of hex2rbg:

  1. Accept short hex like #fff
  2. Algorithm compacity is o(n), should faster than using regex. e.g String.replace, String.split, String.match etc..
  3. Use constant space.
  4. Support rgb and rgba.

you may need remove hex.trim() if you are using IE8.

e.g.

hex2rgb('#fff') //rgb(255,255,255) 
hex2rgb('#fff', 1) //rgba(255,255,255,1) 
hex2rgb('#ffffff') //rgb(255,255,255)  
hex2rgb('#ffffff', 1) //rgba(255,255,255,1)

code:

function hex2rgb (hex, opacity) {
    hex = hex.trim();
    hex = hex[0] === '#' ? hex.substr(1) : hex;
    var bigint = parseInt(hex, 16), h = [];
    if (hex.length === 3) {
        h.push((bigint >> 4) & 255);
        h.push((bigint >> 2) & 255);
    } else {
        h.push((bigint >> 16) & 255);
        h.push((bigint >> 8) & 255);
    }
    h.push(bigint & 255);
    if (arguments.length === 2) {
        h.push(opacity);
        return 'rgba('+h.join()+')';
    } else {
        return 'rgb('+h.join()+')';
    }
}
查看更多
看淡一切
5楼-- · 2018-12-31 02:35
R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");

function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

Use these Function to achive the result without any issue. :)

查看更多
笑指拈花
6楼-- · 2018-12-31 02:35

HTML use the hexadecimal system and the rgb uses the decimal system. so you have to convert the number from hexadecimal to decimal and vice versa.

查看更多
人气声优
7楼-- · 2018-12-31 02:36

// Ignoring hsl notation, color values are commonly expressed as names, rgb, rgba or hex-

// Hex can be 3 values or 6.

// Rgb can be percentages as well as integer values.

// Best to account for all of these formats, at least.

String.prototype.padZero= function(len, c){
    var s= this, c= c || "0", len= len || 2;
    while(s.length < len) s= c + s;
    return s;
}
var colors={
    colornames:{
        aqua: '#00ffff', black: '#000000', blue: '#0000ff', fuchsia: '#ff00ff',
        gray: '#808080', green: '#008000', lime: '#00ff00', maroon: '#800000',
        navy: '#000080', olive: '#808000', purple: '#800080', red: '#ff0000',
        silver: '#c0c0c0', teal: '#008080', white: '#ffffff', yellow: '#ffff00'
    },
    toRgb: function(c){
        c= '0x'+colors.toHex(c).substring(1);
        c= [(c>> 16)&255, (c>> 8)&255, c&255];
        return 'rgb('+c.join(',')+')';
    },
    toHex: function(c){
        var tem, i= 0, c= c? c.toString().toLowerCase(): '';
        if(/^#[a-f0-9]{3,6}$/.test(c)){
            if(c.length< 7){
                var A= c.split('');
                c= A[0]+A[1]+A[1]+A[2]+A[2]+A[3]+A[3];
            }
            return c;
        }
        if(/^[a-z]+$/.test(c)){
            return colors.colornames[c] || '';
        }
        c= c.match(/\d+(\.\d+)?%?/g) || [];
        if(c.length<3) return '';
        c= c.slice(0, 3);
        while(i< 3){
            tem= c[i];
            if(tem.indexOf('%')!= -1){
                tem= Math.round(parseFloat(tem)*2.55);
            }
            else tem= parseInt(tem);
            if(tem< 0 || tem> 255) c.length= 0;
            else c[i++]= tem.toString(16).padZero(2);
        }
        if(c.length== 3) return '#'+c.join('').toLowerCase();
        return '';
    }
}
//var c='#dc149c';
//var c='rgb(100%,25%,0)';
//
var c= 'red';
alert(colors.toRgb(c)+'\n'+colors.toHex(c));
查看更多
登录 后发表回答