PHP 的 Color Range 生成


因為之前有些程式要用到相類似的功能
所以便寫下了這個可以產生顏色範圍值的東東..

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
<?php
// Author: Zeuxis Lo
// Usage: Color_Helper::hex_range("#FFFFF", "#0088FF", 100);

class Color_Helper {

public static function is_rgb($code) {
return is_numeric($code);
}

public static function is_hex($code) {
return self::is_rgb($code) === false;
}

public static function rgb_to_hex($red, $green, $blue) {
return sprintf('#%06X', ($red<&lt;16) + ($green<&lt;8) + $blue);
}

public static function hex_to_rgb($hex) {
if(preg_match('/#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i', $hex, $m) == 1) {
return array('r' => hexdec($m[1]), 'g' => hexdec($m[2]), 'b' => hexdec($m[3]));
} else {
return null;
}
}

public static function hex_range($from_hex, $to_hex, $step = 10) {
$from_rgb = self::hex_to_rgb($from_hex);
$to_rgb = self::hex_to_rgb($to_hex);

$step_rgb['r'] = ($from_rgb['r'] - $to_rgb['r']) / ($step - 1);
$step_rgb['g'] = ($from_rgb['g'] - $to_rgb['g']) / ($step - 1);
$step_rgb['b'] = ($from_rgb['b'] - $to_rgb['b']) / ($step - 1);

$colors = array();

for($i=0; $i< $step; $i++) {
$rgb['r'] = floor($from_rgb['r'] - ($step_rgb['r'] * $i));
$rgb['g'] = floor($from_rgb['g'] - ($step_rgb['g'] * $i));
$rgb['b'] = floor($from_rgb['b'] - ($step_rgb['b'] * $i));

$hex_rgb['r'] = sprintf('%02x', ($rgb['r']));
$hex_rgb['g'] = sprintf('%02x', ($rgb['g']));
$hex_rgb['b'] = sprintf('%02x', ($rgb['b']));

$colors[] = implode("", $hex_rgb);
}
return $colors;
}

}
?>