Redo Calculation of Color Tinting (#3580)

* Redo Calculation of Color Tinting

Fix #3550. Some colors are specified in Excel by specifying a theme color to which a tint is applied. The original PHPExcel algorithm for doing this was developed by trial and error, and is good enough a lot of the time. However, for the issue at hand, the resulting color is detectably different from the calculation that Excel makes. Searching the web, I found https://gist.github.com/Mike-Honey/b36e651e9a7f1d2e1d60ce1c63b9b633 which comes much closer for the case in hand, and for all the other cases that I've looked at. That code depends on Python colorsys package; I have adapted the code from the Python gist and package into a new Php class. This doesn't agree perfectly with Excel. However, if each of the red, green, and blue components (each a value between 0 and 255 inclusive) agree within plus or minus 3 (arbitrary choice) of Excel's result, I think that is good enough.

I have added a new test member which reads from a spreadsheet with Xml altered by hand to set up several theme/tint cells. These tests use the plus-or-minus-3 criterion. They result in 100% code coverage of the new class.

Unsuprisingly, some existing tests failed with the new code. Issue2387Test reads a theme/tint font color, and is changed to use the plus-or-minus-3 criterion, comparing against the color as Excel shows it.

ColorChangeBrightness showed 9 failures with the new code. It consists of calculations not involving a spreadsheet. For that reason, I felt it was sufficient to just do an exact match test, changing the 9 old results for new results confirmed with the Python code. I also added one new test case, the one that kicked off this entire PR.

* Scrutinizer Being Stupid

It strikes again.
This commit is contained in:
oleibman
2023-05-25 13:05:55 -07:00
committed by GitHub
parent 407479f1a2
commit 9a13f526c5
6 changed files with 245 additions and 26 deletions
+1 -16
View File
@@ -362,23 +362,8 @@ class Color extends Supervisor
$green = self::getGreen($hexColourValue, false);
/** @var int $blue */
$blue = self::getBlue($hexColourValue, false);
if ($adjustPercentage > 0) {
$red += (255 - $red) * $adjustPercentage;
$green += (255 - $green) * $adjustPercentage;
$blue += (255 - $blue) * $adjustPercentage;
} else {
$red += $red * $adjustPercentage;
$green += $green * $adjustPercentage;
$blue += $blue * $adjustPercentage;
}
$rgb = strtoupper(
str_pad(dechex((int) $red), 2, '0', 0) .
str_pad(dechex((int) $green), 2, '0', 0) .
str_pad(dechex((int) $blue), 2, '0', 0)
);
return (($rgba) ? 'FF' : '') . $rgb;
return (($rgba) ? 'FF' : '') . RgbTint::rgbAndTintToRgb($red, $green, $blue, $adjustPercentage);
}
/**
+175
View File
@@ -0,0 +1,175 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Style;
/**
* Class to handle tint applied to color.
* Code borrows heavily from some Python projects.
*
* @see https://docs.python.org/3/library/colorsys.html
* @see https://gist.github.com/Mike-Honey/b36e651e9a7f1d2e1d60ce1c63b9b633
*/
class RgbTint
{
private const ONE_THIRD = 1.0 / 3.0;
private const ONE_SIXTH = 1.0 / 6.0;
private const TWO_THIRD = 2.0 / 3.0;
private const RGBMAX = 255.0;
/**
* MS excel's tint function expects that HLS is base 240.
*
* @see https://social.msdn.microsoft.com/Forums/en-US/e9d8c136-6d62-4098-9b1b-dac786149f43/excel-color-tint-algorithm-incorrect?forum=os_binaryfile#d3c2ac95-52e0-476b-86f1-e2a697f24969
*/
private const HLSMAX = 240.0;
/**
* Convert red/green/blue to hue/luminance/saturation.
*
* @param float $red 0.0 through 1.0
* @param float $green 0.0 through 1.0
* @param float $blue 0.0 through 1.0
*
* @return float[]
*/
private static function rgbToHls(float $red, float $green, float $blue): array
{
$maxc = max($red, $green, $blue);
$minc = min($red, $green, $blue);
$luminance = ($minc + $maxc) / 2.0;
if ($minc === $maxc) {
return [0.0, $luminance, 0.0];
}
$maxMinusMin = $maxc - $minc;
if ($luminance <= 0.5) {
$s = $maxMinusMin / ($maxc + $minc);
} else {
$s = $maxMinusMin / (2.0 - $maxc - $minc);
}
$rc = ($maxc - $red) / $maxMinusMin;
$gc = ($maxc - $green) / $maxMinusMin;
$bc = ($maxc - $blue) / $maxMinusMin;
if ($red === $maxc) {
$h = $bc - $gc;
} elseif ($green === $maxc) {
$h = 2.0 + $rc - $bc;
} else {
$h = 4.0 + $gc - $rc;
}
$h = self::positiveDecimalPart($h / 6.0);
return [$h, $luminance, $s];
}
/** @var mixed */
private static $scrutinizerZeroPointZero = 0.0;
/**
* Convert hue/luminance/saturation to red/green/blue.
*
* @param float $hue 0.0 through 1.0
* @param float $luminance 0.0 through 1.0
* @param float $saturation 0.0 through 1.0
*
* @return float[]
*/
private static function hlsToRgb($hue, $luminance, $saturation): array
{
if ($saturation === self::$scrutinizerZeroPointZero) {
return [$luminance, $luminance, $luminance];
}
if ($luminance <= 0.5) {
$m2 = $luminance * (1.0 + $saturation);
} else {
$m2 = $luminance + $saturation - ($luminance * $saturation);
}
$m1 = 2.0 * $luminance - $m2;
return [
self::vFunction($m1, $m2, $hue + self::ONE_THIRD),
self::vFunction($m1, $m2, $hue),
self::vFunction($m1, $m2, $hue - self::ONE_THIRD),
];
}
private static function vFunction(float $m1, float $m2, float $hue): float
{
$hue = self::positiveDecimalPart($hue);
if ($hue < self::ONE_SIXTH) {
return $m1 + ($m2 - $m1) * $hue * 6.0;
}
if ($hue < 0.5) {
return $m2;
}
if ($hue < self::TWO_THIRD) {
return $m1 + ($m2 - $m1) * (self::TWO_THIRD - $hue) * 6.0;
}
return $m1;
}
private static function positiveDecimalPart(float $hue): float
{
$hue = fmod($hue, 1.0);
return ($hue >= 0.0) ? $hue : (1.0 + $hue);
}
/**
* Convert red/green/blue to HLSMAX-based hue/luminance/saturation.
*
* @return int[]
*/
private static function rgbToMsHls(int $red, int $green, int $blue): array
{
$red01 = $red / self::RGBMAX;
$green01 = $green / self::RGBMAX;
$blue01 = $blue / self::RGBMAX;
[$hue, $luminance, $saturation] = self::rgbToHls($red01, $green01, $blue01);
return [
(int) round($hue * self::HLSMAX),
(int) round($luminance * self::HLSMAX),
(int) round($saturation * self::HLSMAX),
];
}
/**
* Converts HLSMAX based HLS values to rgb values in the range (0,1).
*
* @return float[]
*/
private static function msHlsToRgb(int $hue, int $lightness, int $saturation): array
{
return self::hlsToRgb($hue / self::HLSMAX, $lightness / self::HLSMAX, $saturation / self::HLSMAX);
}
/**
* Tints HLSMAX based luminance.
*
* @see http://ciintelligence.blogspot.co.uk/2012/02/converting-excel-theme-color-and-tint.html
*/
private static function tintLuminance(float $tint, float $luminance): int
{
if ($tint < 0) {
return (int) round($luminance * (1.0 + $tint));
}
return (int) round($luminance * (1.0 - $tint) + (self::HLSMAX - self::HLSMAX * (1.0 - $tint)));
}
/**
* Return result of tinting supplied rgb as 6 hex digits.
*/
public static function rgbAndTintToRgb(int $red, int $green, int $blue, float $tint): string
{
[$hue, $luminance, $saturation] = self::rgbToMsHls($red, $green, $blue);
[$red, $green, $blue] = self::msHlsToRgb($hue, self::tintLuminance($tint, $luminance), $saturation);
return sprintf(
'%02X%02X%02X',
(int) round($red * self::RGBMAX),
(int) round($green * self::RGBMAX),
(int) round($blue * self::RGBMAX)
);
}
}
@@ -15,7 +15,11 @@ class Issue2387Test extends TestCase
$reader = IOFactory::createReader('Xlsx');
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('335593', $sheet->getCell('B2')->getStyle()->getFont()->getColor()->getRgb());
// Font color being tested uses theme color with tint.
// Excel shows final color as 305496.
$expectedColor = '305496';
$calculatedColor = $sheet->getCell('B2')->getStyle()->getFont()->getColor()->getRgb();
self::assertSame($expectedColor, RgbTintTest::compareColors($calculatedColor, $expectedColor));
self::assertSame(Fill::FILL_NONE, $sheet->getCell('B2')->getStyle()->getFill()->getFillType());
self::assertSame('FFFFFF', $sheet->getCell('C2')->getStyle()->getFont()->getColor()->getRgb());
self::assertSame('000000', $sheet->getCell('C2')->getStyle()->getFill()->getStartColor()->getRgb());
@@ -0,0 +1,50 @@
<?php
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PHPUnit\Framework\TestCase;
class RgbTintTest extends TestCase
{
public static function compareColors(string $style, string $text): string
{
$styleRed = hexdec(substr($style, 0, 2));
$styleGreen = hexdec(substr($style, 2, 2));
$styleBlue = hexdec(substr($style, 4, 2));
$textRed = hexdec(substr($text, 0, 2));
$textGreen = hexdec(substr($text, 2, 2));
$textBlue = hexdec(substr($text, 4, 2));
$maxDiff = 3;
if (abs($styleRed - $textRed) > $maxDiff) {
return $style;
}
if (abs($styleGreen - $textGreen) > $maxDiff) {
return $style;
}
if (abs($styleBlue - $textBlue) > $maxDiff) {
return $style;
}
return $text;
}
public function testRgbTint(): void
{
$filename = 'tests/data/Reader/XLSX/RgbTint.xlsx';
$reader = IOFactory::createReader('Xlsx');
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$row = 0;
while (true) {
++$row;
$text = (string) $sheet->getCell("B$row");
if ($text === '') {
break;
}
$style = $sheet->getStyle("A$row")->getFill()->getStartColor()->getRgb();
self::assertSame($text, self::compareColors($style, $text), "row $row");
}
$spreadsheet->disconnectWorksheets();
}
}
Binary file not shown.
@@ -9,7 +9,7 @@ return [
],
// RGBA
[
'FF99A8B7',
'FF92A8BE',
'FFAABBCC',
-0.1,
],
@@ -20,17 +20,17 @@ return [
0.1,
],
[
'99A8B7',
'92A8BE',
'AABBCC',
-0.1,
],
[
'FF1919',
'FF1A1A',
'FF0000',
0.1,
],
[
'E50000',
'E60000',
'FF0000',
-0.1,
],
@@ -40,7 +40,7 @@ return [
0.1,
],
[
'E57373',
'FF5959',
'FF8080',
-0.1,
],
@@ -50,7 +50,7 @@ return [
0.15,
],
[
'D80000',
'D90000',
'FF0000',
-0.15,
],
@@ -60,18 +60,23 @@ return [
0.15,
],
[
'D86C6C',
'FF4646',
'FF8080',
-0.15,
],
[
'FFF783',
'FFF984',
'FFF008',
0.5,
],
[
'7F7804',
'847D00',
'FFF008',
-0.5,
],
'issue 3550' => [
'558ED5',
'1F497D',
0.39997558519241921,
],
];