|
本帖最后由 只为设计 于 2016-8-30 14:07 编辑
- private int Rgb2Hsl(int r, int g, int b)
- {
- float h = 0;
- float s = 0;
- float l = 0;
- float max = Math.Max(Math.Max(r, g), b);
- float min = Math.Min(Math.Min(r, g), b);
- if (max == min)
- {
- h = 0;
- }
- else
- {
- if (max == r)
- {
- if (g >= b)
- {
- h = 255 / 6 * (g - b) / (max - min) + 0;
- }
- else
- {
- h = 255 / 6 * (g - b) / (max - min) + 255;
- }
- }
- if (max == g & max != r)
- {
- h = 255 / 6 * (b - r) / (max - min) + 255 / 3;
- }
- if (max == b && max != g)
- {
- h = 255 / 6 * (r - g) / (max - min) + 255 * 2 / 3;
- }
- }
- if (h >= (int)h + 0.5f)
- {
- h = (int)h + 1;
- }
- l = (max + min) / 2;
- if (max + min == 255)
- {
- l = 128;
- }
- if (l >= (int)l + 0.5f)
- {
- l = (int)l + 1;
- }
- if (l == 0 || max == min)
- {
- s = 0;
- }
- else
- {
- if (l <= 255 / 2)
- {
- s = 255 * (max - min) / (max + min);
- }
- else
- {
- s = 255 * (max - min) / (2 * 255 - (max + min));
- }
- }
- if (s >= (int)s + 0.5f)
- {
- s = (int)s + 1;
- }
- int hsl = (int)h + (int)s * 256 + (int)l * 256 * 256;
- return hsl;
- }
复制代码这是我根据维基百科上的公式做出的C#代码
使用时
- int hsl = Rgb2Hsl(r, g, b);
- int h = hsl % 256;
- int s = (hsl / 256) % 256;
- int l = (hsl / 256 / 256) % 256;
复制代码
|
|