Skip to content

Commit

Permalink
Merge pull request #2 from saxation/bugfix/sqmk#130/rgb-value-fix
Browse files Browse the repository at this point in the history
sqmk#130 Fix color higher than 255
  • Loading branch information
neoteknic authored Jan 11, 2018
2 parents c7ffcdf + 5bba324 commit e468972
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
19 changes: 14 additions & 5 deletions library/Phue/Helper/ColorConversion.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public static function convertRGBToXY($red, $green, $blue)
'bri' => round($xyz['y'] * 255)
);
}

/**
* Converts XY (and brightness) values to RGB
*
Expand All @@ -76,24 +76,33 @@ 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) {
$color[$key] = 12.92 * $normalized;
} 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;
}
}
7 changes: 7 additions & 0 deletions tests/Phue/Test/Helper/ColorConversionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit e468972

Please sign in to comment.