PHP Colour Format Conversion

Allows the setting of getting of colour in various formats: RGB, HSL, CMY and CMYK.
The colour is stored as an RGB array. Since RGB to HSL and HSL to RGB conversion is quite heavy, it might be better if you also stored the HSL value if it is going to be called frequently. However, I have a strong dislike of storing the same data in more than one place and since I will only do these conversions a couple of times.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
<!–?php
/**
 * pjlColour
 *
 * Set and return colours in different formats: RGB, HSL and css
 *
 * @package pjlColour
 *
 * @version 1.0
 * @copyright Peter Lux
 * @author Peter Lux
 * @link http://www.plux.co.uk/php-colour-format-conversion/
 * @license GPL http://www.opensource.org/licenses/gpl-license.html
 *
 * HSL format is Hue(0-360), Saturation (0-100), Luminance (0-100%)
 * RGB, CMY, CMYK have colour values of 0-255
 *
 *
 */


/**
 *  Set and return colours in different formats: RGB, HSL and css
 *
 */

class pjlColour {

    const RED = 0;
    const GREEN = 1;
    const BLUE = 2;

    const HUE = 0;
    const SATURATION = 1;
    const LUMINANCE = 2;

    protected $rgb = array(0,0,0);

    /**
    * Constructor.
    * @param int $r Red intensity 0 to 255.
    * @param int $g Green intensity 0 to 255.
    * @param int $b Blue intensity 0 to 255.
    *
    * @return void.
    */

    function __construct($r=0,$g=0,$b=0) {
        $this-&gt;rgb[self::RED] = $r;
        $this-&gt;rgb[self::GREEN] = $g;
        $this-&gt;rgb[self::BLUE] = $b;
    }

    /**
    * setRGB.
    *
    * sets the colour using RGB values
    *
    * @param int $r Red intensity 0 to 255.
    * @param int $g Green intensity 0 to 255.
    * @param int $b Blue intensity 0 to 255.
    *
    * @return void.
    */

    function setRGB($r,$g,$b) {
        $this-&gt;rgb[self::RED] = $r;
        $this-&gt;rgb[self::GREEN] = $g;
        $this-&gt;rgb[self::BLUE] = $b;
    }
    /**
    * getRGB.
    *
    * @return array (red, green, blue).
    */

    function getRGB() {
        return ($this-&gt;rgb);
    }

    /**
    * getHexDigit($hex).
    * @param int $hex digit to convert.
    *
    * @return string the hexidecimal representation of the digit with leading zero.
    */

    private function getHexDigit($hex) {
        $hexDigit = dechex($hex);

        // Add a leading zero if necessary
        if(strlen($hexDigit) == 1) {
            $hexDigit = "0" . $hexDigit;
        }
        return $hexDigit;
    }

    /**
    * setHex($hex).
    * @param int $hex string in css hexidecimal with leading #.
    *
    * @return true.
    */

    public function setHex($hex) {
        if (substr($hex,0,1) != ‘#’)
            throw new Exception (‘"’.$hex.‘" is not a valid hex colour’);
        $hex = substr($hex,1);

        $d = ‘[a-fA-F0-9]’;

        // Make sure $hex is valid
        if (preg_match("/^($d$d)($d$d)($d$d)\$/", $hex, $rgb)) {
            $this-&gt;rgb[self::RED] = hexdec($rgb[1]);
            $this-&gt;rgb[self::GREEN] = hexdec($rgb[2]);
            $this-&gt;rgb[self::BLUE] = hexdec($rgb[3]);
        } else if (preg_match("/^($d)($d)($d)$/", $hex, $rgb)) {
            $this-&gt;rgb[self::RED] = hexdec($rgb[1] . $rgb[1]);
            $this-&gt;rgb[self::GREEN] = hexdec($rgb[2] . $rgb[2]);
            $this-&gt;rgb[self::BLUE] = hexdec($rgb[3] . $rgb[3]);
        } else {
            throw new Exception ("cannot convert hex ‘$hex‘ to RGB");
        }
        return(true);
    }

    /**
    * getHex().
    * @param void.
    *
    * @return string current colour in css hexidecimal notation.
    */

    function getHex() {
        return ‘#’.$this-&gt;getHexDigit($this-&gt;rgb[self::RED]).$this-&gt;getHexDigit($this-&gt;rgb[self::GREEN]).$this-&gt;getHexDigit($this-&gt;rgb[self::BLUE]);
    }

    /**
    * getHSL().
    * @param void.
    *
    * @return array(hue, saturation, Luminance).
    *
    * algorithum based on
    * http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/
    *
    */

    function getHSL() {
        $Saturation = 0;
        $Luminance = 0;
        $Hue = 0;

        $r = $this-&gt;rgb[self::RED]/255;
        $g = $this-&gt;rgb[self::GREEN]/255;
        $b = $this-&gt;rgb[self::BLUE]/255;

        $min = min($r,$g,$b);
        $max = max($r,$g,$b);

        $Luminance = ($min + $max)/2;
        if ($min != $max) {
            if ($Luminance &lt; 0.5) {
                $Saturation = ($max$min)/($max+$min);
            } else {
                $Saturation = ( $max$min)/(2.0$max$min);
            }
            if ($max == $r) {
                $Hue = ($g$b)/($max$min);
            } else if ($max == $g) {
                $Hue = 2.0 + ($b$r)/($max$min);
            } else {
                $Hue = 4.0 + ($r$g)/($max$min);
            }
        }
        $Hue = $Hue * 60;
        if ($Hue &lt; 0) {
            $Hue = $Hue + 360;
        }

        return(array(round($Hue,2),round($Saturation*100,2),round($Luminance*100,2)));
    }

    /**
    * setHSL($h,$s,$l).
    * @param float Hue 0-360.
    * @param float Saturation 0 – 100%
    * @param float Luminance 0 – 100%
    *
    * @return void.
    *
    * algorithum based on
    * http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/
    *
    */

    function setHSL($h,$s,$l) {
        // convert values to fractions
        $h = $h /360;
        $s = $s / 100;
        $l = $l / 100;

        // if there is no saturation then it is greyscale
        if ($s == 0) {
            $this-&gt;rgb[self::RED] = $l * 255;
            $this-&gt;rgb[self::GREEN] = $this-&gt;rgb[self::RED];
            $this-&gt;rgb[self::BLUE] = $this-&gt;rgb[self::RED];
        } else {
            if ($l &lt; 0.5) {
                $temporary_1 = $l * (1 + $s);
            } else {
                $temporary_1 = $l + $s $l * $s;
            }

            $temporary_2 = 2 * $l $temporary_1;

            // $temporary is $h + 0.333 for red, $h for green and $h – 0.333 for blue. Therefore I multiply
            // 0.333 by (1-$i) which is 1,0,-1
            for ($i=0 ; $i&lt;3 ; $i++) {
                $temporary = $h + (1$i)*0.333;
                if ($temporary &gt; 1)
                    $temporary = $temporary 1;
                else if ($temporary &lt; 0 )
                    $temporary += 1;

                if (6 * $temporary &lt; 1) {
                    $this-&gt;rgb[$i] = intval(($temporary_2 + ($temporary_1 $temporary_2) * 6 * $temporary) * 255);
                } else if (2 * $temporary &lt; 1) {
                    $this-&gt;rgb[$i] = intval($temporary_1 * 255);
                } else if (3 * $temporary &lt; 2) {
                    $this-&gt;rgb[$i] = intval(($temporary_2 + ($temporary_1 $temporary_2) * (0.666 $temporary) * 6) * 255);
                } else {
                    $this-&gt;rgb[$i] = intval($temporary_2 * 255);
                }
            }
        }
    }

    /**
    * function setCMY($c,$m,$y).
    * @param int cyan intensity (0-255)
    * @param int Magenta intensity (0-255)
    * @param int Yellow intensity (0-255)
    *
    * @return void.
    *
    */

    public function setCMY($c, $m, $y) {
        setRGB(255$c, 255$m, 255$y);
    }

    /**
    * getCMY().
    * @param void.
    *
    * @return array(cyan, magenta, yellow).
    *
    */

    public function getCMY() {
        return(array(255$this-&gt;rgb[self::RED],255$this-&gt;rgb[self::GREEN],255$this-&gt;rgb[self::BLUE]));
    }

    /**
    * function setCMYK($c,$m,$y).
    * @param int cyan intensity (0-255)
    * @param int Magenta intensity (0-255)
    * @param int Yellow intensity (0-255)
    *
    * @return void.
    *
    */

    public function setCMYK($c, $m, $y, $k) {
        setRGB((255$c)*(255$k), (255$m)*(255$k), (255$y)*(255$k));
    }

    /**
    * getCMYK().
    * @param void.
    *
    * @return array(cyan, magenta, yellow).
    *
    */

    public function getCMYK() {
        $k = 255 max($this-&gt;rgb);
        return(array(round(255*((255$this-&gt;rgb[self::RED]$k)/(255$k)),0),
                     round(255*((255$this-&gt;rgb[self::GREEN]$k)/(255$k)),0),
                     round(255*((255$this-&gt;rgb[self::BLUE]$k)/(255$k)),0),
                     $k));
    }

    /**
    * function increaseLuminance($increase).
    * @param float % increase in Luminance (use negative $increase to decrease).
    *
    * @return void.
    *
    * if luminance is not in range 0-100 it corrects to 0 or 100
    */

    public function increaseLuminance($increase) {
        $hsl = $this-&gt;getHSL();
        $l = $hsl[2] + $increase;
        if ($l &gt; 100) $l = 100;
        if ($l &lt; 0) $l = 0;
        $this-&gt;setHSL($hsl[self::HUE], $hsl[self::SATURATION], $l);
    }

    /**
    * function increaseSaturation($increase).
    * @param float % increase in Saturation (use negative $increase to decrease).
    *
    * @return void.
    *
    * if saturation is not in range 0-100 it corrects to 0 or 100
    */

    public function increaseSaturation($increase) {
        $hsl = $this-&gt;getHSL();
        $s = $hsl[1] + $increase;
        if ($s &gt; 100) $s = 100;
        if ($s &lt; 0) $s = 0;
        $this-&gt;setHSL($hsl[self::HUE], $s, $hsl[self::LUMINANCE]);
    }

    /**
    * function increaseSaturation($increase).
    * @param float degree increase in Hue (use negative $increase to decrease).
    *
    * @return void.
    *
    * Will wrap round if $hue is out of 0-360 range
    * this can be used to set complimenary colour by calling -&gt;increaseHue(180)
    */

    public function increaseHue($increase) {
        $increase = $increase % 360;
        $hsl = $this-&gt;getHSL();
        $h = $hsl[self::HUE] + $increase;
        if ($h &gt; 360) $h = $h 360;
        if ($h &lt; 0) $h = $h + 360;
        $this-&gt;setHSL($h, $hsl[self::SATURATION], $hsl[self::LUMINANCE]);
    }
}
?–>

Example of use:




1
2
3
4
5
6
7
8
9
10
11
$colour = new pjlColour(140,80,120); // create new colour with R,G,B values
$colour-&gt;getHex();  // get hex value i.e. #8c5078
$colour-&gt;getHSL();  // returns an array containing HSL values (0-360, 0-100, 0-100)
$colour-&gt;getCMY();  // returns an array of the CMY values (0-255)
$colour-&gt;getCMYK(); // returns an array of the CMYK values (0-255)
$colour-&gt;setHSL(200,50,50); // set HSL value hue:200 with 50% saturation and luminance
$colour-&gt;setCMYK(0,127,127,50); // set CMYK values
$colour2 = clone $colour;  // get a copy of the colour
$colour2-&gt;increaseHue(180); // increase Hue by 180 degrees – wraps round after 360
$colour2-&gt;increaseSaturation(10) // increase the saturation by 10%
$colour2-&gt;increaseLuminance(20) // decrease the Luminance by 20%
Share

Categories:

Tags:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha: * Time limit is exhausted. Please reload CAPTCHA.

Recent Posts


Old Posts


Categories