From cb2547efa32a4f9b9f386c7e3d2b1b70582a1fae Mon Sep 17 00:00:00 2001 From: erixreyes Date: Fri, 25 Jul 2025 10:40:39 +0800 Subject: [PATCH] Issue #2489: Adding RGB to HSL function --- gfx/src/nsColor.cpp | 35 +++++++++++++++++++++++++++++++++++ gfx/src/nsColor.h | 5 +++++ 2 files changed, 40 insertions(+) diff --git a/gfx/src/nsColor.cpp b/gfx/src/nsColor.cpp index 359f9fde47..f8070ddfba 100644 --- a/gfx/src/nsColor.cpp +++ b/gfx/src/nsColor.cpp @@ -348,6 +348,41 @@ NS_HSL2RGB(float h, float s, float l) return NS_RGB(r, g, b); } +// RGB to HSL conversion function +// The uint8_t RGB parameters are expected to be in the range 0-255 +// Returns HSL values in the range: H[0-1], S[0-1], L[0-1] +void +NS_RGB2HSL(uint8_t aR, uint8_t aG, uint8_t aB, float* aH, float* aS, float* aL) +{ + float r = aR / 255.0f; + float g = aG / 255.0f; + float b = aB / 255.0f; + + float max = std::max(r, std::max(g, b)); + float min = std::min(r, std::min(g, b)); + float h, s, l = (max + min) / 2.0f; + + if (max == min) { + h = s = 0.0f; // achromatic + } else { + float d = max - min; + s = l > 0.5f ? d / (2.0f - max - min) : d / (max + min); + + if (max == r) { + h = (g - b) / d + (g < b ? 6.0f : 0.0f); + } else if (max == g) { + h = (b - r) / d + 2.0f; + } else { + h = (r - g) / d + 4.0f; + } + h /= 6.0f; + } + + *aH = h; + *aS = s; + *aL = l; +} + const char* NS_RGBToColorName(nscolor aColor) { diff --git a/gfx/src/nsColor.h b/gfx/src/nsColor.h index 2f21c91bf2..72ec5c7a86 100644 --- a/gfx/src/nsColor.h +++ b/gfx/src/nsColor.h @@ -113,6 +113,11 @@ const char * const * NS_AllColorNames(size_t *aSizeArray); // the float parameters are all expected to be in the range 0-1 nscolor NS_HSL2RGB(float h, float s, float l); +// function to convert from RGB color space to HSL color space +// the uint8_t RGB parameters are expected to be in the range 0-255 +// the float HSL parameters will be set to values in the range 0-1 +void NS_RGB2HSL(uint8_t aR, uint8_t aG, uint8_t aB, float* aH, float* aS, float* aL); + // Return a color name for the given nscolor. If there is no color // name for it, returns null. If there are multiple possible color // names for the given color, the first one in nsColorNameList.h