From 5bba32429159b35c048e6b93e519c3bd4c1f4529 Mon Sep 17 00:00:00 2001 From: Alex Buis Date: Wed, 27 Dec 2017 14:23:26 +0100 Subject: [PATCH] #130 Fix color higher than 255 - fixed coding standards in color conversion tool. - added unit test for the 0..255 range fix. --- library/Phue/Helper/ColorConversion.php | 19 ++++++++++++++----- .../Phue/Test/Helper/ColorConversionTest.php | 7 +++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/library/Phue/Helper/ColorConversion.php b/library/Phue/Helper/ColorConversion.php index 4e0dde0..2e9c2c2 100644 --- a/library/Phue/Helper/ColorConversion.php +++ b/library/Phue/Helper/ColorConversion.php @@ -59,7 +59,7 @@ public static function convertRGBToXY($red, $green, $blue) 'bri' => round($xyz['y'] * 255) ); } - + /** * Converts XY (and brightness) values to RGB * @@ -76,12 +76,13 @@ public static function convertXYToRGB($x, $y, $bri = 255) $xyz['y'] = $bri / 255; $xyz['x'] = ($xyz['y'] / $y) * $x; $xyz['z'] = ($xyz['y'] / $y) * $z; - + // Convert to RGB using Wide RGB D65 conversion $color['red'] = $xyz['x'] * 1.656492 - $xyz['y'] * 0.354851 - $xyz['z'] * 0.255038; $color['green'] = -$xyz['x'] * 0.707196 + $xyz['y'] * 1.655397 + $xyz['z'] * 0.036152; $color['blue'] = $xyz['x'] * 0.051713 - $xyz['y'] * 0.121364 + $xyz['z'] * 1.011530; - + + $maxValue = 0; foreach ($color as $key => $normalized) { // Apply reverse gamma correction if ($normalized <= 0.0031308) { @@ -89,11 +90,19 @@ public static function convertXYToRGB($x, $y, $bri = 255) } else { $color[$key] = (1.0 + 0.055) * pow($normalized, 1.0 / 2.4) - 0.055; } - + $color[$key] = max(0, $color[$key]); + if ($maxValue < $color[$key]) { + $maxValue = $color[$key]; + } + } + foreach ($color as $key => $normalized) { + if ($maxValue > 1) { + $color[$key] /= $maxValue; + } // Scale back from a maximum of 1 to a maximum of 255 $color[$key] = round($color[$key] * 255); } - + return $color; } } diff --git a/tests/Phue/Test/Helper/ColorConversionTest.php b/tests/Phue/Test/Helper/ColorConversionTest.php index 31c1be2..64119a1 100644 --- a/tests/Phue/Test/Helper/ColorConversionTest.php +++ b/tests/Phue/Test/Helper/ColorConversionTest.php @@ -68,5 +68,12 @@ public function testConvertXYToRGB() $this->assertEquals($rgb['red'], 61); $this->assertEquals($rgb['green'], 178); $this->assertEquals($rgb['blue'], 112); + + // Test to make sure single RGB values falls within 0..255 range. + // old situation this was r -18, g 186, b -613. + $rgb = ColorConversion::convertXYToRGB(0.1979, 1.5005, 81); + $this->assertEquals($rgb['red'], 0); + $this->assertEquals($rgb['green'], 186); + $this->assertEquals($rgb['blue'], 0); } }