前言
RGB色彩空间:红,绿和蓝(Red,Green,Blue),其适用于机器采样,目前的显示器颜色即由这三种基色构成,RGB的取值范围在0 ~ 255之间;
HSL色彩空间(HSB/HSV):色调,饱和度和亮度(Hue,Saturation,Lightness/Brightness/Value),其更符合人类的直观感觉,HSL的取值在0 ~ 1之间。
RGB转换成HSL:
#include <algorithm>
using std::min;
using std::max;
void RGB2HSL(TColor AColor, double &H,double &S,double &L)
{
double R,G,B,Max,Min,del_R,del_G,del_B,del_Max;
R = GetRValue(AColor) / 255.0; //Where RGB values = 0 ÷ 255
G = GetGValue(AColor) / 255.0;
B = GetBValue(AColor) / 255.0;
Min = min(R, min(G, B)); //Min. value of RGB
Max = max(R, max(G, B)); //Max. value of RGB
del_Max = Max - Min; //Delta RGB value
L = (Max + Min) / 2.0;
if (del_Max == 0) //This is a gray, no chroma...
{
//H = 2.0/3.0; //Windows下S值为0时,H值始终为160(2/3*240)
H = 0; //HSL results = 0 ÷ 1
S = 0;
}
else //Chromatic data...
{
if (L < 0.5) S = del_Max / (Max + Min);
else S = del_Max / (2 - Max - Min);
del_R = (((Max - R) / 6.0) + (del_Max / 2.0)) / del_Max;
del_G = (((Max - G) / 6.0) + (del_Max / 2.0)) / del_Max;
del_B = (((Max - B) / 6.0) + (del_Max / 2.0)) / del_Max;
if (R == Max) H = del_B - del_G;
else if (G == Max) H = (1.0 / 3.0) + del_R - del_B;
else if (B == Max) H = (2.0 / 3.0) + del_G - del_R;
if (H < 0) H += 1;
if (H > 1) H -= 1;
}
}
HSL转换为RGB:
TColor HSL2RGB(double H,double S,double L)
{
double R,G,B;
double var_1, var_2;
if (S == 0) //HSL values = 0 ÷ 1
{
R = L * 255.0; //RGB results = 0 ÷ 255
G = L * 255.0;
B = L * 255.0;
}
else
{
if (L < 0.5) var_2 = L * (1 + S);
else var_2 = (L + S) - (S * L);
var_1 = 2.0 * L - var_2;
R = 255.0 * Hue2RGB(var_1, var_2, H + (1.0 / 3.0));
G = 255.0 * Hue2RGB(var_1, var_2, H);
B = 255.0 * Hue2RGB(var_1, var_2, H - (1.0 / 3.0));
}
return TColor(RGB(R,G,B));
}
//---------------------------------------------------------------------------
double Hue2RGB(double v1, double v2, double vH)
{
if (vH < 0) vH += 1;
if (vH > 1) vH -= 1;
if (6.0 * vH < 1) return v1 + (v2 - v1) * 6.0 * vH;
if (2.0 * vH < 1) return v2;
if (3.0 * vH < 2) return v1 + (v2 - v1) * ((2.0 / 3.0) - vH) * 6.0;
return (v1);
}
附表(HSL/V/B在各种环境下的取值范围):
Applications | Space | H Range | S Range | L/V/B Range | |
Paint Shop Pro | HSL | 0 - 255 | 0 - 255 | L | 0 - 255 |
Gimp | HSV | 0 - 360° | 0 - 100 | V | 0 - 100 |
Photoshop | HSV | 0 - 360° | 0 - 100% | B | 0 - 100% |
Windows | HSL | 0 - 240 | 0 - 240 | L | 0 - 240 |
Linux / KDE | HSV | 0 - 360° | 0 - 255 | V | 0 - 255 |
GTK | HSV | 0 - 360° | 0 - 1.0 | V | 0 - 1.0 |
Java (awt.Color) | HSV | 0 - 1.0 | 0 - 1.0 | B | 0 - 1.0 |
Apple | HSV | 0 - 360° | 0 - 100% | L | 0 - 100% |