0

I wanted to find a way to code a program that would convert ANY rgb including ones with negative integers into a hex number, like this software.

http://www.javascripter.net/faq/rgbtohex.htm

I have this already but it doesn't seem to be working with the rgb:

rgb(-5, 231, -17)

function rgb2hex(rgb){
 rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
 return (rgb && rgb.length === 4) ? "#" +
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

Thanks to anyone who can help!

aritro33
  • 227
  • 6
  • 13

1 Answers1

0

Try this,

    function colorToHex(color) {
        if (color.substr(0, 1) === '#') {
            return color;
        }
        var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);

        var red = parseInt(digits[2]);
        var green = parseInt(digits[3]);
        var blue = parseInt(digits[4]);

        var rgb = blue | (green << 8) | (red << 16);
        return digits[1] + '#' + rgb.toString(16);
    };

    colorToHex('rgb(120, 120, 240)');

Ref: http://haacked.com/archive/2009/12/29/convert-rgb-to-hex.aspx/

Krish R
  • 22,583
  • 7
  • 50
  • 59