#include <stdio.h>
#include <stdlib.h>
#include "hsl_rgb.h"
#define MAX_RGB_V 255 //RGB分辨率
static unsigned char hue_2_rgb(float v1,float v2, float vh)
{
float value;
if (vh < 0)
{
vh += 1;
}
if(vh > 1)
{
vh -= 1;
}
if((vh * 6) < 1)
{
value = (v1 + (v2 - v1) * 6 * vh);
return value * MAX_RGB_V;
}
if((vh * 2) < 1)
{
return (v2 * MAX_RGB_V);
}
if((vh * 3) < 2)
{
value = (v1 + (v2 - v1) * (2.0f / 3.0f - vh) * 6);
return value * MAX_RGB_V;
}
return v1 * MAX_RGB_V;
}
void hsl_to_rgb(int hue,int saturation,int lightness,rgb_t *rgb)
{
float H,S,L;
float var_2,var_1;
H = (float)hue / 65535;
S = (float)saturation / 65535;
L = (float)lightness / 256;
// printf("H: %f,S:%f, L:%f\n",H,S,L);
if(S == 0)
{
rgb->R = L;
rgb->G = L;
rgb->BL = L;
}
else
{
if( L < 0.5)
{
var_2 = L * (S + 1);
}
else
{
var_2 = (L + S) - (S * L);
}
var_1 = 2 * L - var_2;
// printf("var1:%f,var2,%f\n",var_1,var_2);
rgb->R = hue_2_rgb(var_1,var_2,H + 1.0f / 3.0f);
rgb->G = hue_2_rgb(var_1,var_2,H);
rgb->BL = hue_2_rgb(var_1,var_2,H - 1.0f / 3.0f);
}
}
void rgb_to_hsl(unsigned char red,unsigned char green,unsigned char blue,hsl_t *hsl)
{
float H,S,L;
float rf,gf,bf;
float maxf,minf;
/* 第一步把rgb转换为浮点数0~1 */
rf = (float)red / 255;
gf = (float)green / 255;
bf = (float)blue / 255;
printf("rgbf:%f,%f,%f\n",rf,gf,bf);
/* 第二步找出rf,gf,bf,最大值 */
maxf = rf > gf? rf:gf;
maxf = maxf > bf? maxf:bf;
minf = rf < gf? rf:gf;
minf = minf < bf? minf:bf;
/* 第三步计算亮度值 */
L = (maxf + minf) / 2;
/* 如果最大值等于最小值则为灰色 */
if(maxf == minf)
{
S = 0;
H = 0;
}
else
{
/* 计算S */
if(L < 0.5)
{
S = (maxf - minf) / (maxf + minf);
}
else
{
S = (maxf - minf) / (2 - maxf - minf);
}
/* 计算H */
if(rf == maxf)
{
H = (gf - bf) / (maxf - minf);
}
if(gf == maxf)
{
H = 2 + (bf - rf) / (maxf - minf);
}
if(bf == maxf)
{
H = 4 + (rf - gf) / (maxf - minf);
}
/* */
H = H*60;
if(H < 0)
{
H += 360;
}
}
hsl->hue = H * 65535 / 360;
hsl->saturation = S * 65535;
hsl->lightness = L * 255;
printf("HSL:%x,%x,%x\n",hsl->hue,hsl->saturation,hsl->lightness);
}
int main()
{
int rgb_value;
hsl_t hsl_buf;
rgb_t rgb_buf;
hsl_to_rgb(0xe48a,0xffff,0xb8,&rgb_buf);
printf("RGB %x\n",rgb_buf);
rgb_to_hsl(rgb_buf.R, rgb_buf.G, rgb_buf.BL,&hsl_buf);
return(0);
}
评论0