How to convert RGB to HSL in C?

匆匆过客 提交于 2020-01-23 11:47:51

问题


How do I convert RGB to HSL in C/C++?

(Note: This is a (short) self-answer -- I posted it here so people can find it quickly with a search.)


回答1:


Translating the code from here, you get:

// Assuming sizeof(unsigned int) == 4 * sizeof(unsigned char)
unsigned int RgbToHsl(unsigned int rgb)  // Alpha value is simply passed through
{
#ifdef __cplusplus
    using std::max;
    using std::min;
#endif
    double
        r = (rgb >> (0 * CHAR_BIT)) & UCHAR_MAX,
        g = (rgb >> (1 * CHAR_BIT)) & UCHAR_MAX,
        b = (rgb >> (2 * CHAR_BIT)) & UCHAR_MAX;
    r /= UCHAR_MAX;
    g /= UCHAR_MAX;
    b /= UCHAR_MAX;
    double
        maxv = max(max(r, g), b),
        minv = min(min(r, g), b),
        h = 0, s = 0, d = maxv - minv,
        l = (maxv + minv) / 2;
    if (maxv != minv)
    {
        s = l > 0.5 ? d / (2 - maxv - minv) : d / (maxv + minv);
        if (maxv == r) { h = (g - b) / d + (g < b ? 6 : 0); }
        else if (maxv == g) { h = (b - r) / d + 2; }
        else if (maxv == b) { h = (r - g) / d + 4; }
        h /= 6;
    }
    return ((unsigned int)(h * UCHAR_MAX) << (0 * CHAR_BIT)) |
           ((unsigned int)(s * UCHAR_MAX) << (1 * CHAR_BIT)) |
           ((unsigned int)(l * UCHAR_MAX) << (2 * CHAR_BIT)) |
           (((rgb >> (3 * CHAR_BIT)) & UCHAR_MAX) << (3 * CHAR_BIT));
}

Assuming the order is RGBA where R is the least significant byte.



来源:https://stackoverflow.com/questions/12380682/how-to-convert-rgb-to-hsl-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!