Bin will be removed on June 1, 2014 in favor of http://gist.github.com. Please save all your pastes before then. So long, and thanks for all the fish!×
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
 
    public static $xyzToRgb = array(
        array(3.24071, -0.969258, 0.0556352),
        array(-1.53726, 1.87599, -0.203996),
        array(-0.498571, 0.0415557, 1.05707)
    );
 
    public function temperature2rgb($temperature) {
        // Fit for CIE Daylight illuminant
        if ($temperature <= 4000) {
            $xD = 0.27475e9 / ($temperature * $temperature * $temperature) - 0.98598e6 / ($temperature * $temperature) + 1.17444e3 / $temperature + 0.145986;
        } else if ($temperature <= 7000) {
            $xD = -4.6070e9 / ($temperature * $temperature * $temperature) + 2.9678e6 / ($temperature * $temperature) + 0.09911e3 / $temperature + 0.244063;
        } else {
            $xD = -2.0064e9 / ($temperature * $temperature * $temperature) + 1.9018e6 / ($temperature * $temperature) + 0.24748e3 / $temperature + 0.237040;
        }
        $yD = -3 * $xD * $xD + 2.87 * $xD - 0.275;
 
        // Fit for Blackbody using CIE standard observer function at 2 degrees
        //xD = -1.8596e9/(T*T*T) + 1.37686e6/(T*T) + 0.360496e3/T + 0.232632;
        //yD = -2.6046*xD*xD + 2.6106*xD - 0.239156;
 
        // Fit for Blackbody using CIE standard observer function at 10 degrees
        //xD = -1.98883e9/(T*T*T) + 1.45155e6/(T*T) + 0.364774e3/T + 0.231136;
        //yD = -2.35563*xD*xD + 2.39688*xD - 0.196035;
 
        $X = $xD / $yD;
        $Y = 1;
        $Z = (1 - $xD - $yD) / $yD;
        $max = 0;
        $rgb = array();
        for ($c = 0; $c < 3; $c++) {
            $rgb[$c] = $X * self::$xyzToRgb[0][$c] + $Y * self::$xyzToRgb[1][$c] + $Z * self::$xyzToRgb[2][$c];
            if ($rgb[$c] > $max) {
                $max = $rgb[$c];
            }
        }
        for ($c = 0; $c < 3; $c++) {
            $rgb[$c] = $rgb[$c] / $max;
        }
 
        return self::_rgbArray($rgb);
    }
 
/**
 * @link http://en.wikipedia.org/wiki/Chromaticity
 *
 * @param type $colour
 */
    public static function rgb2temperature($r, $g, $b) {
        $colour = array($r, $g, $b);
 
        $tMin = 2000;
        $tMax = 23000;
 
        for ($temperature = ($tMax + $tMin) / 2; $tMax - $tMin > 0.1; $temperature = ($tMax + $tMin) / 2) {
            $rgb = array_values(self::temperature2rgb($temperature));
            if($rgb[2] / $rgb[0] > $colour[2] / $colour[0]) {
                $tMax = $temperature;
            } else {
                $tMin = $temperature;
            }
        }
 
        return $temperature;
    }