1typedef struct RgbColor
2{
3 unsigned char r;
4 unsigned char g;
5 unsigned char b;
6} RgbColor;
7
8typedef struct HsvColor
9{
10 unsigned char h;
11 unsigned char s;
12 unsigned char v;
13} HsvColor;
14
15RgbColor HsvToRgb(HsvColor hsv)
16{
17 RgbColor rgb;
18 unsigned char region, remainder, p, q, t;
19
20 if (hsv.s == 0)
21 {
22 rgb.r = hsv.v;
23 rgb.g = hsv.v;
24 rgb.b = hsv.v;
25 return rgb;
26 }
27
28 region = hsv.h / 43;
29 remainder = (hsv.h - (region * 43)) * 6;
30
31 p = (hsv.v * (255 - hsv.s)) >> 8;
32 q = (hsv.v * (255 - ((hsv.s * remainder) >> 8))) >> 8;
33 t = (hsv.v * (255 - ((hsv.s * (255 - remainder)) >> 8))) >> 8;
34
35 switch (region)
36 {
37 case 0:
38 rgb.r = hsv.v; rgb.g = t; rgb.b = p;
39 break;
40 case 1:
41 rgb.r = q; rgb.g = hsv.v; rgb.b = p;
42 break;
43 case 2:
44 rgb.r = p; rgb.g = hsv.v; rgb.b = t;
45 break;
46 case 3:
47 rgb.r = p; rgb.g = q; rgb.b = hsv.v;
48 break;
49 case 4:
50 rgb.r = t; rgb.g = p; rgb.b = hsv.v;
51 break;
52 default:
53 rgb.r = hsv.v; rgb.g = p; rgb.b = q;
54 break;
55 }
56
57 return rgb;
58}
59
60HsvColor RgbToHsv(RgbColor rgb)
61{
62 HsvColor hsv;
63 unsigned char rgbMin, rgbMax;
64
65 rgbMin = rgb.r < rgb.g ? (rgb.r < rgb.b ? rgb.r : rgb.b) : (rgb.g < rgb.b ? rgb.g : rgb.b);
66 rgbMax = rgb.r > rgb.g ? (rgb.r > rgb.b ? rgb.r : rgb.b) : (rgb.g > rgb.b ? rgb.g : rgb.b);
67
68 hsv.v = rgbMax;
69 if (hsv.v == 0)
70 {
71 hsv.h = 0;
72 hsv.s = 0;
73 return hsv;
74 }
75
76 hsv.s = 255 * long(rgbMax - rgbMin) / hsv.v;
77 if (hsv.s == 0)
78 {
79 hsv.h = 0;
80 return hsv;
81 }
82
83 if (rgbMax == rgb.r)
84 hsv.h = 0 + 43 * (rgb.g - rgb.b) / (rgbMax - rgbMin);
85 else if (rgbMax == rgb.g)
86 hsv.h = 85 + 43 * (rgb.b - rgb.r) / (rgbMax - rgbMin);
87 else
88 hsv.h = 171 + 43 * (rgb.r - rgb.g) / (rgbMax - rgbMin);
89
90 return hsv;
91}
92