2

Following this question and many others, I'm trying to convert an rgb value to a hex value.

Copying/pasting the most used and accepted answer, I've made this script

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

function rgbToHex(rgb) {

            var colors = rgb.split("(")
            colors = colors[1].split(")")
            colors = colors[0].split(",")

            var r = 255 - parseInt(colors[0])
            var g = 255 - parseInt(colors[1])
            var b = 255 - parseInt(colors[2])

            return componentToHex(r) + componentToHex(g) + componentToHex(b);
        }

alert(rgbToHex("rgb(0, 51, 255)"))

Result:

ffcc00

Expected result:

0033ff

Why is it not working?

Community
  • 1
  • 1
Saturnix
  • 10,130
  • 17
  • 64
  • 120

2 Answers2

3

Use the parseInt result directly, not 255 minus the value:

var r = parseInt(colors[0])
var g = parseInt(colors[1])
var b = parseInt(colors[2])

You're currently producing the exact opposite color by outputting values complementary to (rather than equivalent to) the input values.

apsillers
  • 112,806
  • 17
  • 235
  • 239
2

Instead of 255 - parseInt(colors[i]), it should be parseInt(colors[i]).

In your current implementation - if red is 0, 255 - 0 = 255, which in hex is FF.

Jeffrey Blake
  • 9,659
  • 6
  • 43
  • 65
Kyri Elia
  • 997
  • 9
  • 18