How do you get the hue of a #xxxxxx colour?
Asked Answered
W

5

41

How do you extract the hue component of a color given as #rrggbb?

Warily answered 17/9, 2010 at 1:12 Comment(0)
C
50

If you search for how to convert RGB to HSL, you'll find a number of algorithms, including in the Wikipedia article linked by Sergey.

First, extract the RGB components of the hex color notation.

var color='#c7d92c'; // A nice shade of green.
var r = parseInt(color.substr(1,2), 16); // Grab the hex representation of red (chars 1-2) and convert to decimal (base 10).
var g = parseInt(color.substr(3,2), 16);
var b = parseInt(color.substr(5,2), 16);

That'll get you the byte (0-255) representation of your color. In this case, 199, 217, 44.

You can then use the formulae from the Wikipedia article to calculate hue, or shamelessly steal someone else's code:

function rgbToHsl(r, g, b){
    r /= 255, g /= 255, b /= 255;
    var max = Math.max(r, g, b), min = Math.min(r, g, b);
    var h, s, l = (max + min) / 2;

    if(max == min){
        h = s = 0; // achromatic
    }else{
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch(max){
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }

    return [h, s, l];
}

(See the source page for documentation and a hslToRgb() function.)

We can now put those two snippets together and get the hue:

var hue = rgbToHsl(r, g, b)[0] * 360;

The [0] is to grab the hue – the function returns an array ([h,s,l]). We multiply by 360 since hue is returned as a value between 0 and 1; we want to convert it to degrees.

With the example color of #c7d92c, hue will be ~66.24. Photoshop's color picker says the hue of that color is 66° so it looks like we're good!

Coddle answered 17/9, 2010 at 1:56 Comment(1)
For reference: I made a Java version of this code: https://mcmap.net/q/138832/-android-use-hex-color-for-google-maps-markerAeromancy
H
15

The wikipedia article has a formula which looks like something that can easily be implemented:

http://en.wikipedia.org/wiki/Hue#Computing_hue_from_RGB

Edit: here's a function which uses those formulas:

function getHue(color) {
  var r = parseInt(color.substring(0,2),16)/255;
  var g = parseInt(color.substring(2,4),16)/255;
  var b = parseInt(color.substring(4,6),16)/255;

  var hue;
  if ((r >= g) && (g >= b)) {
      hue = 60*(g-b)/(r-b);
  } else if ((g > r) && (r >= b)) {
      hue = 60*(2 - (r-b)/(g-b));
  }
  //... continue here
  return hue;
}

alert(getHue('FF0000')); // correctly returns 0
alert(getHue('408000')); // correctly returns 90
alert(getHue('0000FF')); // not implemented yet

Just continue using the formulas from the table in that wikipedia article for other angles.

Hellkite answered 17/9, 2010 at 1:21 Comment(4)
Note that formula will fail for black/white/greyscale, when r === g === bMilitiaman
I am often amazed by how some people reason about code. Your code, returns hue when it hasn't yet been initialized. At least in theory.Ritz
@IharobAlAsimi: It's not code, it's incomplete pseudo-code, not suitable for copy-pasting. For the cases which are not yet implemented, it would return undefined, which kinda makes sense.Hellkite
Yes, it does make sense ... I didn't read the "Just continue using ..." before, as I was trying to to roll my own function.Ritz
B
9
hue = Atan2(1.732050808 * (G - B), (2 * R - G - B)) * 57.295779513;

http://en.wikipedia.org/wiki/Hue

or

hue = Atan2(sqr(3) * (G - B), 2 * R - G - B)

The result will be in polar units. Multiply by 180 and divide by pi to convert to degrees.

Basuto answered 4/1, 2014 at 3:31 Comment(0)
S
7

I have stumbled on this issue as well after years, that's how I have worked around it.

Credits: Brandon Mathis of hslpicker.com, code was taken from here

function hexToRgb (color) {
  let hex = color[0] === '#' ? color.slice(1) : color;
  let c;

  // expand the short hex by doubling each character, fc0 -> ffcc00
  if (hex.length !== 6) {
    hex = ((() => {
      const result = [];
      for (c of Array.from(hex)) {
        result.push(`${c}${c}`);
      }
      return result;
    })()).join('');
  }
  const colorStr = hex.match(/#?(.{2})(.{2})(.{2})/).slice(1);
  const rgb = colorStr.map(col => parseInt(col, 16));
  rgb.push(1);
  return rgb;
}

function rgbToHsl (rgb) {
  const r = rgb[0] / 255;
  const g = rgb[1] / 255;
  const b = rgb[2] / 255;

  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  const diff = max - min;
  const add = max + min;

  const hue =
    min === max ?
      0
    : r === max ?
      (((60 * (g - b)) / diff) + 360) % 360
    : g === max ?
      ((60 * (b - r)) / diff) + 120
    :
      ((60 * (r - g)) / diff) + 240;

  const lum = 0.5 * add;

  const sat =
    lum === 0 ?
      0
    : lum === 1 ?
      1
    : lum <= 0.5 ?
      diff / add
    :
      diff / (2 - add);

  const h = Math.round(hue);
  const s = Math.round(sat * 100);
  const l = Math.round(lum * 100);
  const a = rgb[3] || 1;

  return [h, s, l, a];
}

I have written a small wrapper around those 2 functions to convert array of hex colors to arrays of strings describing H / S / L components

function hexToHsl (color) {
  const rgb = hexToRgb(color);
  const hsl = rgbToHsl(rgb);
  return `original: ${ color } - H: ${ hsl[0] } S: ${ hsl[1] } L: ${ hsl[2] }`;
}

Usage:

var colors = ['#51bce6','#6dcff6','#829CBD','#565a5c']
colors.map(color => hexToHsl(color))

=> ["original: #51bce6 - H: 197 S: 75 L: 61", "original: #6dcff6 - H: 197 S: 88 L: 70", "original: #829CBD - H: 214 S: 31 L: 63", "original: #565a5c - H: 200 S: 3 L: 35"]
Shoeshine answered 13/11, 2017 at 18:19 Comment(0)
A
2

There are well written libraries available on npm now, for example:

https://www.npmjs.com/package/color-convert

Thankfully it uses an MIT License, like most libraries on npm.

Using that library, you want to go from hex to HSL* or HSV* and take the first value:

var convert = require('color-convert');
let hue = convert.hex.hsv('DEADBF')[0];

Before using require(), you have to install npm, and run npm install --save color-convert in your project folder. I believe you can also just drop the library in a script tag in the browser.

*HSL: hue, saturation, lightness. HSV: hue, saturation, value.

Arv answered 10/5, 2019 at 17:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.