Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
ColorConverter
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
4 / 4
5
100.00% covered (success)
100.00%
1 / 1
 rgbToCmyk
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
2
 cmykToRgb
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 rgbToGray
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 grayToRgb
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Phpdftk\Color;
6
7/**
8 * Lossless color model conversions between RGB, CMYK, and Gray.
9 *
10 * RGB↔CMYK uses the standard subtractive model. RGB→Gray uses
11 * ITU-R BT.601 luma coefficients (0.299R + 0.587G + 0.114B) to
12 * match perceived brightness.
13 */
14final class ColorConverter
15{
16    public static function rgbToCmyk(RgbColor $rgb): CmykColor
17    {
18        $r = $rgb->r;
19        $g = $rgb->g;
20        $b = $rgb->b;
21        $k = 1.0 - max($r, $g, $b);
22        if ($k >= 1.0) {
23            return new CmykColor(0.0, 0.0, 0.0, 1.0);
24        }
25        $c = (1.0 - $r - $k) / (1.0 - $k);
26        $m = (1.0 - $g - $k) / (1.0 - $k);
27        $y = (1.0 - $b - $k) / (1.0 - $k);
28        return new CmykColor(
29            max(0.0, min(1.0, $c)),
30            max(0.0, min(1.0, $m)),
31            max(0.0, min(1.0, $y)),
32            max(0.0, min(1.0, $k)),
33        );
34    }
35
36    public static function cmykToRgb(CmykColor $cmyk): RgbColor
37    {
38        $c = $cmyk->c;
39        $m = $cmyk->m;
40        $y = $cmyk->y;
41        $k = $cmyk->k;
42        return new RgbColor(
43            max(0.0, min(1.0, (1.0 - $c) * (1.0 - $k))),
44            max(0.0, min(1.0, (1.0 - $m) * (1.0 - $k))),
45            max(0.0, min(1.0, (1.0 - $y) * (1.0 - $k))),
46        );
47    }
48
49    public static function rgbToGray(RgbColor $rgb): GrayColor
50    {
51        $gray = 0.299 * $rgb->r + 0.587 * $rgb->g + 0.114 * $rgb->b;
52        return new GrayColor(max(0.0, min(1.0, $gray)));
53    }
54
55    public static function grayToRgb(GrayColor $gray): RgbColor
56    {
57        return new RgbColor($gray->gray, $gray->gray, $gray->gray);
58    }
59}