-
Notifications
You must be signed in to change notification settings - Fork 0
/
HSVtoRGB.c
85 lines (72 loc) · 1.56 KB
/
HSVtoRGB.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
Simple functions to convert HSV color space values to RGB and vice versa.
*/
#define MIN(a,b) (a < b ? a : b)
#define MINTHREE(a,b,c) MIN(MIN(a,b),c)
#define MAX(a,b) (a > b ? a : b)
#define MAXTHREE(a,b,c) MAX(MAX(a,b),c)
void HSVtoRGB(int* r, int* g, int* b, int h, int s, int v)
{
int f;
long p, q, t;
if (s == 0)
{
*r = *g = *b = v;
return;
}
f = ((h % 60) * 255) / 60;
h /= 60;
p = (v * (256 - s)) / 256;
q = (v * (256 - (s * f) / 256)) / 256;
t = (v * (256 - (s * (256 - f)) / 256)) / 256;
switch (h) {
case 0:
*r = v;
*g = t;
*b = p;
break;
case 1:
*r = q;
*g = v;
*b = p;
break;
case 2:
*r = p;
*g = v;
*b = t;
break;
case 3:
*r = p;
*g = q;
*b = v;
break;
case 4:
*r = t;
*g = p;
*b = v;
break;
default:
*r = v;
*g = p;
*b = q;
break;
}
}
void RGBtoHSV(int* h, int* s, int* v, int r, int g, int b) {
int rgbMin, rgbMax;
rgbMin = MINTHREE(r, g, b);
rgbMax = MAXTHREE(r, g, b);
*v = rgbMax;
if (*v == 0) {
*h = *s = 0;
return;
}
*s = 255 * ((long)(rgbMax - rgbMin)) / *v;
if (*s == 0) {
*h = 0;
return;
}
if (rgbMax == r) *h = 0 + 43 * (g - b) / (rgbMax - rgbMin);
else if (rgbMax == g) *h = 85 + 43 * (b - r) / (rgbMax - rgbMin);
else *h = 171 + 43 * (r - g) / (rgbMax - rgbMin);
}