RGB Do Hex I Hex Do RGB

Jak przekonwertować kolory w formacie RGB na format Hex i odwrotnie?

Na przykład Konwertuj '#0080C0' na (0, 128, 192).

Author: Michał Perłakowski, 2011-04-11

30 answers

Do konwersji RGB NA hex wykonamy następujące czynności i dodamy wymagane zero padding:

function componentToHex(c) {
    var hex = c.toString(16);
    return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
    return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

alert( rgbToHex(0, 51, 255) ); // #0033ff

Konwersja w drugą stronę:

function hexToRgb(hex) {
    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";

Wreszcie, alternatywna wersja rgbToHex(), jak omówiono w odpowiedzi @ casablanca i zasugerowano w komentarzach przez @cwolves:

function rgbToHex(r, g, b) {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

Aktualizacja 3 Grudnia 2012

Oto wersja hexToRgb(), która również parsuje skrócony tryplet szesnastkowy, taki jak "#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";
 957
Author: Tim Down,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-22 10:14:25

Alternatywna wersja hexToRgb:

function hexToRgb(hex) {
    var bigint = parseInt(hex, 16);
    var r = (bigint >> 16) & 255;
    var g = (bigint >> 8) & 255;
    var b = bigint & 255;

    return r + "," + g + "," + b;
}

Edit: 3/28/2017 Oto inne podejście , które wydaje się być jeszcze szybsze

function hexToRgbNew(hex) {
  var arrBuff = new ArrayBuffer(4);
  var vw = new DataView(arrBuff);
  vw.setUint32(0,parseInt(hex, 16),false);
  var arrByte = new Uint8Array(arrBuff);

  return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
}

Edycja: 8/11/2017 Nowe podejście powyżej po kolejnych testach nie jest szybsze :(. Chociaż jest to zabawny alternatywny sposób.

 113
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-22 14:41:30

Oto moja wersja:

  function rgb2hex(red, green, blue) {
        var rgb = blue | (green << 8) | (red << 16);
        return '#' + (0x1000000 + rgb).toString(16).slice(1)
  }

  function hex2rgb(hex) {
        // long version
        r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
        if (r) {
                return r.slice(1,4).map(function(x) { return parseInt(x, 16); });
        }
        // short version
        r = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
        if (r) {
                return r.slice(1,4).map(function(x) { return 0x11 * parseInt(x, 16); });
        }
        return null;
  }
 38
Author: FelipeC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-25 20:59:55

Zakładam, że masz na myśli zapis szesnastkowy w stylu HTML, czyli #rrggbb. Twój kod jest prawie poprawny, tylko że masz odwróconą kolejność. Powinno być:

var decColor = red * 65536 + green * 256 + blue;

Również użycie przesunięć bitowych może ułatwić odczyt:

var decColor = (red << 16) + (green << 8) + blue;
 25
Author: casablanca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-11 15:48:08

ECMAScript 6 Wersja Tim Down ' s answer

Konwersja RGB NA hex

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

console.log(rgbToHex(0, 51, 255)); // '#0033ff'

Konwersja hex NA RGB

Zwraca tablicę [r, g, b]. Działa również ze skróconymi trójkami sześciokątnymi, takimi jak "#03F".

const hexToRgb = hex =>
  hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
             ,(m, r, g, b) => '#' + r + r + g + g + b + b)
    .substring(1).match(/.{2}/g)
    .map(x => parseInt(x, 16))

console.log(hexToRgb("#0033ff")) // [0, 51, 255]
console.log(hexToRgb("#03f")) // [0, 51, 255]

Bonus: RGB Do hex przy użyciu metody padStart()

const rgbToHex = (r, g, b) => '#' + [r, g, b]
  .map(x => x.toString(16).padStart(2, '0')).join('')

console.log(rgbToHex(0, 51, 255)); // '#0033ff'

Należy zauważyć, że ta odpowiedź wykorzystuje najnowsze funkcje ECMAScript, które nie są obsługiwane w starszych przeglądarkach. Jeśli chcesz, aby ten kod praca we wszystkich środowiskach, do kompilacji kodu należy użyć Babel.

 22
Author: Michał Perłakowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-19 08:15:05

Ten kod akceptuje warianty #ffffff i # ffffff oraz nieprzezroczystość.

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(',')+')';
}
 21
Author: falko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-09 19:33:37
function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}
 16
Author: rezoner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-31 12:12:09

Jednoliniowy HEX funkcyjny do RGBA

Obsługuje zarówno krótkie #fff, jak i długie #ffffff formy.
Obsługuje kanał alfa (krycie).
Nie obchodzi mnie, czy hash jest określony, czy nie, działa w obu przypadkach.

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(',') + ')';
}

Przykłady:

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)  
 8
Author: Denis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-27 22:34:07

To może być użyte do uzyskania kolorów z obliczonych propeties stylu:

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

 8
Author: K-Gun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-15 23:12:29

// ignorując notację hsl, wartości kolorów są zwykle wyrażane jako nazwy, rgb, rgba lub hex -

// Hex może mieć 3 wartości lub 6.

/ / Rgb może być zarówno wartością procentową, jak i całkowitą.

// najlepiej uwzględnić przynajmniej wszystkie te formaty.

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));
 6
Author: kennebec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-11 16:41:38

@ Tim, aby dodać do swojej odpowiedzi (to trochę niezręczne dopasowanie tego do komentarza).

Jak pisałem, znalazłem funkcję rgbtohex zwraca łańcuch z elementami po punkcie i wymaga, aby wartości r, g, b mieściły się w zakresie 0-255.

Jestem pewien, że to może wydawać się oczywiste dla większości, ale zajęło mi dwie godziny, aby dowiedzieć się, i do tego czasu oryginalna metoda ballooned do 7 linijek, zanim zdałem sobie sprawę, że mój problem jest gdzie indziej. Tak więc w interesie oszczędzania czasu innym & hassle, oto mój nieco zmieniony kod, który sprawdza wstępne wymagania i przycina zbędne bity łańcucha.

function rgbToHex(r, g, b) {
    if(r < 0 || r > 255) alert("r is out of bounds; "+r);
    if(g < 0 || g > 255) alert("g is out of bounds; "+g);
    if(b < 0 || b > 255) alert("b is out of bounds; "+b);
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);
}
 5
Author: Matt Stevens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-18 23:53:47

Jeśli chcesz porównać dwie wartości kolorów (podane jako rgb, Nazwa koloru lub wartość szesnastkowa)lub przekonwertować na wartość szesnastkową, użyj obiektu HTML5 canvas.

    var canvas = document.createElement("canvas");
    var ctx = this.canvas.getContext('2d');

    ctx.fillStyle = "rgb(pass,some,value)";
    var temp =  ctx.fillStyle;
    ctx.fillStyle = "someColor";

    alert(ctx.fillStyle == temp);
 4
Author: Anton Putov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-05 00:23:45

Możesz być po coś takiego?

function RGB2HTML(red, green, blue)
{
    return '#' + red.toString(16) +
           green.toString(16) +
           blue.toString(16);
}

alert(RGB2HTML(150, 135, 200));

Wyświetla #9687c8

 3
Author: Miquel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-11 15:52:24

Dla 3 cyfr hekstorgb funkcję Tim Down można poprawić jak poniżej:

var hex2Rgb = function(hex){
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})|([a-f\d]{1})([a-f\d]{1})([a-f\d]{1})$/i.exec(hex);
  return result ? {        
    r: parseInt(hex.length <= 4 ? result[4]+result[4] : result[1], 16),
    g: parseInt(hex.length <= 4 ? result[5]+result[5] : result[2], 16),
    b: parseInt(hex.length <= 4 ? result[6]+result[6] : result[3], 16),
    toString: function() {
      var arr = [];
      arr.push(this.r);
      arr.push(this.g);
      arr.push(this.b);
      return "rgb(" + arr.join(",") + ")";
    }
  } : null;
};
 3
Author: Erhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-02 11:41:45

(2017) Proste funkcje strzałek ES6

Nie mogę się oprzeć podzieleniu się tym dla tych, którzy mogą pisać jakieś nowoczesne funkcjonalne / kompozytowe js za pomocą ES6. Oto kilka zręcznych jednolinijek, których używam w module kolorów, który interpoluje kolory do wizualizacji danych.

Zauważ, że to w ogóle nie obsługuje kanału alfa.

const arrayToRGBString = rgb => `rgb(${rgb.join(',')})`;
const hexToRGBArray = hex => hex.match(/[A-Za-z0-9]{2}/g).map(v => parseInt(v, 16));
const rgbArrayToHex = rgb => `#${rgb.map(v => v.toString(16).padStart(2, '0')).join('')}`;
const rgbStringToArray = rgb => rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).splice(1, 3)
  .map(v => Number(v));
const rgbStringToHex = rgb => rgbArrayToHex(rgbStringToArray(rgb));
 3
Author: Ron Gilchrist,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-24 09:15:00

Moja wersja hex2rbg:

  1. Accept short hex like #fff
  2. kompresji algorytmu jest o (n), powinien szybciej niż przy użyciu regex. np. g String.replace, String.split, String.match itd..
  3. Użyj stałej przestrzeni.
  4. Obsługa rgb i rgba.

Możesz potrzebować usunąć hex.trim() jeśli używasz IE8.

Np.

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)

Kod:

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()+')';
    }
}
 3
Author: Eric Chen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-23 23:27:55

Potrzebowałem funkcji, która również akceptuje nieprawidłowe wartości jak

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

To jest spin off @ cwolves odpowiedz

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();
}
 2
Author: Chad Scira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-24 18:38:41

Chociaż ta odpowiedź jest mało prawdopodobna, aby idealnie pasowała do pytania, może być jednak bardzo przydatna.

  1. Utwórz dowolny element losowy

var toRgb = document.createElement('div');

  1. Ustaw dowolny poprawny Styl na kolor, który chcesz przekonwertować

toRg.style.color = "hsl(120, 60%, 70%)";

  1. wywołanie właściwości style ponownie

> toRgb.style.color;

< "rgb(133, 225, 133)" twój kolor został przekonwertowany na Rgb

Działa dla: Hsl, Hex

Nie działa dla: nazwane kolory

 2
Author: Entarra De'Lacord,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-25 06:07:18
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
 1
Author: user2240578,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-24 10:54:18

Natknąłem się na ten problem, ponieważ chciałem zaakceptować dowolną wartość koloru i być w stanie dodać krycie, więc zrobiłem ten szybki jQuery plugin, który wykorzystuje natywne płótno na nowoczesnych przeglądarkach. Wygląda na to, że działa świetnie.

Edit

Okazuje się, że nie mogę wymyślić, jak zrobić z niego odpowiednią Wtyczkę jQuery, więc przedstawię ją jako zwykłą funkcję.

//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;
};
 1
Author: Patrick Roberts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-22 23:18:40
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}

Użyj tych funkcji, aby uzyskać wynik bez żadnych problemów. :)

 1
Author: user3767878,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-04 13:35:52

Pracuję z danymi XAML, które mają format hex #Aarrggbb (Alpha, Red, Green, Blue). Korzystając z powyższych odpowiedzi, oto moje rozwiązanie:

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/

 1
Author: Benson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-27 18:59:14

Do konwersji bezpośrednio z jQuery możesz spróbować:

  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'))
 1
Author: Luis Amor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-04 15:03:35
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;
 1
Author: user3237573,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-15 04:17:56

Wersja skrócona, która przyjmuje ciąg znaków:

function rgbToHex(a){
  a=a.replace(/[^\d,]/g,"").split(","); 
  return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)
}

document.write(rgbToHex("rgb(255,255,255)"));

Aby sprawdzić, czy nie jest już szesnastkowy

function rgbToHex(a){
  if(~a.indexOf("#"))return a;
  a=a.replace(/[^\d,]/g,"").split(","); 
  return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)
}

document.write("rgb: "+rgbToHex("rgb(255,255,255)")+ " -- hex: "+rgbToHex("#e2e2e2"));
 1
Author: Aart den Braber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-17 15:31:49

Biorąc pod uwagę wiele odpowiedzi tylko częściowo odpowiedzieć na pytanie (albo z RGB Do HEX lub w drugą stronę) pomyślałem, że mogę umieścić moją częściową odpowiedź, jak również.

Miałem podobny problem i chciałem zrobić coś takiego: wprowadzić dowolny poprawny kolor CSS(HSL(a), RGB (a), HEX lub nazwę koloru) i 1. możliwość dodawania lub usuwania wartości alfa, 2. zwraca obiekt rgb(a). Napisałem wtyczkę dokładnie w tym celu. Można go znaleźć na GitHub (wymaga jQuery, ale jeśli chcesz, możesz go rozwidlić i zrobić wersję waniliową). Oto strona demo . Możesz spróbować samemu i zobaczyć wyniki generowane w locie.

Skopiuję i wkleję opcje tutaj:

Generator RGB przyjmuje jeden argument, kolor i udostępnia trzy opcje: asObject, addAlpha i removeAlpha. Gdy te trzy opcje zostaną pominięte, kolor RGB zostanie zwrócony jako ciąg znaków.

$.rgbGenerator("white")
// Will return rgb(255,255,255)

Zauważ, że domyślnie włączone są komponenty Alfa. Jeśli wejście wartość zawiera wartość alfa, wyjście będzie w formacie RGBa.

$.rgbGenerator("hsla(0,100%,50%,0.8)")
// Will return rgba(255,0,0,0.8)

Możesz wyłączyć to zachowanie, ustawiając removeAlpha na true. Spowoduje to usunięcie dowolnej wartości alfa z początkowego koloru HSLa lub RGBa.

$.rgbGenerator("hsla(0,100%,50%,0.8)", {removeAlpha: true})
// Will return rgb(255,0,0)

Jeśli natomiast chcesz dodać kanał alfa, możesz to zrobić, ustawiając addAlpha na dowolną wartość z zakresu od 0 do 1. Gdy wejście jest nieprzejrzystym kolorem, zostanie dodana wartość alfa. Jeśli jest przezroczysty, podana wartość nadpisze Składnik Alfa wejścia.

$.rgbGenerator("hsl(0,100%,50%)", {addAlpha: 0.4})
// Will return rgba(255,0,0,0.4)
$.rgbGenerator("hsla(0,100%,50%,0.8)", {addAlpha: 0.4})
// Will return rgba(255,0,0,0.4)

Wreszcie możliwe jest również wyświetlenie koloru RGB(a) jako obiektu. Składa się z r, g, b i opcjonalnie a.

$.rgbGenerator("hsla(0,100%,50%,0.8)", {asObject: true})
/* Will return
{
  "r": 255,
  "g": 0,
  "b": 0,
  "a": 0.8
}
*/
$.rgbGenerator("hsla(0,100%,50%,0.8)", {asObject: true}).r
// Will return 255
 1
Author: Bram Vanroy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-03 09:07:13

Najwyżej oceniona odpowiedź Tima Down zapewnia najlepsze rozwiązanie, jakie widzę do konwersji na RGB. Podoba mi się to rozwiązanie do konwersji Hex lepiej, ponieważ zapewnia najbardziej zwięzłe sprawdzanie granic i zero padding do konwersji na Hex.

function RGBtoHex (red, green, blue) {
  red = Math.max(0, Math.min(~~this.red, 255));
  green = Math.max(0, Math.min(~~this.green, 255));
  blue = Math.max(0, Math.min(~~this.blue, 255));

  return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6);
};

Użycie operatorów left shift '

 1
Author: srolfe26,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-16 21:33:47

Znalazłem to i ponieważ myślę, że jest to dość proste i ma testy walidacyjne i obsługuje wartości alfa( opcjonalnie), to pasuje do przypadku.

Po prostu skomentuj wiersz regex, jeśli wiesz, co robisz i jest to trochę szybsze.

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(",")+")";
}
 1
Author: redestructa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-23 11:23:38

Zupełnie inne podejście do konwersji kodu kolorów hex NA RGB bez regex

Obsługuje zarówno format #FFF, jak i #FFFFFF na podstawie długości łańcucha. Usuwa # z początku łańcucha i dzieli każdy znak łańcucha i konwertuje go do base10 i dodaje go do odpowiedniego indeksu na podstawie jego pozycji.

//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'));
 1
Author: Rehan Haider,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-10 12:02:47

HTML używa systemu szesnastkowego, A rgb systemu dziesiętnego. więc musisz przekonwertować liczbę z szesnastkowego do dziesiętnego i odwrotnie.

 0
Author: reporter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-11 15:48:17