Skip to content

Commit

Permalink
changed HSL to HSV conversion method, fixes issue #27
Browse files Browse the repository at this point in the history
  • Loading branch information
ozdemirburak committed Jan 30, 2021
1 parent 6d3d75e commit 7bbb586
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 6 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

All Notable changes to `iris` will be documented in this file.

## 2021-01-31
- Fix HSL to HSV conversion.

## 2020-12-06
- PHP 8.0 support.

Expand Down
9 changes: 5 additions & 4 deletions src/Color/Hsl.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,17 @@ public function toHsla()
}

/**
* Source: https://en.wikipedia.org/wiki/HSL_and_HSV#Interconversion
*
* @throws \OzdemirBurak\Iris\Exceptions\InvalidColorException
* @return \OzdemirBurak\Iris\Color\Hsv
*/
public function toHsv()
{
[$h, $s, $l] = $this->valuesInUnitInterval();
$t = $s * $l < 0.5 ? $l : 1 - $l;
$s = 2 * $t / ($l + $t);
$l += $t;
$code = implode(',', [round($h * 360), round($s * 100), round($l * 100)]);
$v = $s * min($l, 1 - $l) + $l;
$s = $v ? 2 * (1 - $l / $v) : 0;
$code = implode(',', [round($h * 360), round($s * 100), round($v * 100)]);
return new Hsv($code);
}

Expand Down
7 changes: 5 additions & 2 deletions src/Color/Hsv.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,17 @@ public function toHex()
}

/**
* Source: https://en.wikipedia.org/wiki/HSL_and_HSV#Interconversion
*
* @throws \OzdemirBurak\Iris\Exceptions\InvalidColorException
* @return \OzdemirBurak\Iris\Color\Hsl
*/
public function toHsl()
{
[$h, $s, $v] = $this->valuesInUnitInterval();
$l = (2 - $s) * $v / 2;
$s = $l && $l < 1 ? $s * $v / ($l < 0.5 ? $l * 2 : 2 - $l * 2) : $s;
$l = $v * (1 - $s / 2);
$m = min($l, 1 - $l);
$s = $l && $l < 1 ? ($v - $l) / $m : 0;
$code = implode(',', [round($h * 360), round($s * 100), round($l * 100)]);
return new Hsl($code);
}
Expand Down
10 changes: 10 additions & 0 deletions tests/Color/FactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,14 @@ public function testAmbiguousString()
$this->expectException(\OzdemirBurak\Iris\Exceptions\AmbiguousColorString::class);
Factory::init('100, 20%, 5%');
}

/**
* @throws \OzdemirBurak\Iris\Exceptions\AmbiguousColorString
* @throws \OzdemirBurak\Iris\Exceptions\InvalidColorException
*/
public function testSelfConversion()
{
$this->assertEquals(Factory::init("hsv(0, 36%, 72%)")->toHsl()->toHsv(), new Hsv("hsv(0, 36%, 72%)"));
$this->assertEquals(Factory::init("hsl(0, 33%, 66%)")->toHsv()->toHsl(), new Hsl("hsl(0, 33%, 66%)"));
}
}

0 comments on commit 7bbb586

Please sign in to comment.