Sinaesthetic
Sinaesthetic

Reputation: 12211

Why does hsl blue keep coming out as red when converted back to rgb?

I've used a number of "solutions" out there but nothing seems to fix this. Currently, I'm using the Newman's implementation of the HslColor class (http://richnewman.wordpress.com/hslcolor-class/) to do some color randomization within color themes. It mostly works just fine. In this particular scenario though, an HSL value (210,61,62) which is a blue goes into the class, but its RGB values are calculated as 82,51,48 which is a red. I've tried a number of solutions for converting HSL back to RGB but they either don't work at all (causing overflows etc) or give me back a red instead of a blue.

I suspected that maybe it was because my Hue is in degrees (0-360) and all of the algorithms are expecting something else (not noted in their posts). So I tried changing from degrees like this:

var h = Hue * (Math.PI / 180d);

But I got the same thing.

Like I said, I've tried a number of solutions that were suggested here on SO. Currently, I'm using this to make the conversion back to RGB:

[DllImport("shlwapi.dll")]
public static extern int ColorHLSToRGB(int h, int l, int s);

public string ToHexString()
{
    var h = Hue*(Math.PI/180.0d);
    var i = ColorHLSToRGB(Convert.ToInt32(h), Convert.ToInt32(Saturation),
        Convert.ToInt32(Luminosity));
    var c = ColorTranslator.FromWin32(i);

    return string.Format("#{0}{1}{2}", 
        c.R.ToString("X2"), 
        c.G.ToString("X2"), 
        c.B.ToString("X2"));
}

This seems to work fine with most colors, but this is a particular scenario where it does not. I did consider the loss of resolution between float, double and int (between solutions) but it didn't seem to make a difference other than the encountered overflows. Any ideas?

Upvotes: 1

Views: 217

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70701

According to the code you're referencing, it looks to me that is expect HSL values ranging between 0.0 and 240.0. In particular, you only get the HSL-based constructor if you pass values that are of type double. If you pass ints for the constructor, it treats that as an RGB color, not HSL. Seeing as how in RGB space (210,61,62) is a shade of red, that seems consistent with your observation.

One would normally expect that you'd then just get the same RGB value back out. Unfortunately, you didn't post any actual code related to the problem you're asking about, so I can't say specifically why you're seeing the exact behavior you describe. But for sure, as far as that HSLColor class is concerned, you can't give it an HSL value triplet of (210,61,62). That just doesn't work.

Upvotes: 3

Related Questions