@@ -8,6 +8,11 @@ inline uint8_t clamp(int x)
88 return (x<0 ) ? 0 : ((x>255 ) ? 255 : uint8_t (x));
99}
1010
11+ inline double clamp (double x)
12+ {
13+ return std::max (0.0 , std::min (x, 1.0 ));
14+ }
15+
1116void ColorSys::rgb2hsl (uint8_t red, uint8_t green, uint8_t blue, uint16_t & hue, float & saturation, float & luminance)
1217{
1318 QColor color (red,green,blue);
@@ -60,9 +65,9 @@ void ColorSys::yuv2rgb(uint8_t y, uint8_t u, uint8_t v, uint8_t &r, uint8_t &g,
6065
6166void ColorSys::rgb2okhsv (uint8_t red, uint8_t green, uint8_t blue, double & hue, double & saturation, double & value)
6267{
63- ok_color::HSV color = ok_color::srgb_to_okhsv ({ static_cast <float >(red) / 255 .F ,
64- static_cast <float >(green) / 255 .F ,
65- static_cast <float >(blue) / 255 .F
68+ ok_color::HSV color = ok_color::srgb_to_okhsv ({ static_cast <double >(red) / 255.0 ,
69+ static_cast <double >(green) / 255.0 ,
70+ static_cast <double >(blue) / 255.0
6671 });
6772 hue = color.h ;
6873 saturation = color.s ;
@@ -71,8 +76,9 @@ void ColorSys::rgb2okhsv(uint8_t red, uint8_t green, uint8_t blue, double & hue,
7176
7277void ColorSys::okhsv2rgb (double hue, double saturation, double value, uint8_t & red, uint8_t & green, uint8_t & blue)
7378{
74- ok_color::RGB color = ok_color::okhsv_to_srgb ({ static_cast <float >(hue), static_cast <float >(saturation), static_cast <float >(value) });
75- red = static_cast <uint8_t >(std::lround (color.r * 255 ));
76- green = static_cast <uint8_t >(std::lround (color.g * 255 ));
77- blue = static_cast <uint8_t >(std::lround (color.b * 255 ));
79+ ok_color::RGB color = ok_color::okhsv_to_srgb ({ hue, saturation, value });
80+ // okhsv_to_srgb can output rgb colors with slightly negative components. Clamping them before casting prevents rollover errors
81+ red = static_cast <uint8_t >(std::lround (clamp (color.r ) * 255.0 ));
82+ green = static_cast <uint8_t >(std::lround (clamp (color.g ) * 255.0 ));
83+ blue = static_cast <uint8_t >(std::lround (clamp (color.b ) * 255.0 ));
7884}
0 commit comments