php获取图片主要色值,rgb hex 转换


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
<?php

*图片主要(三通道)颜色判断
*author cuitengwei
*2014/1/16
*/

function ($imgUrl) {
$imageInfo = getimagesize($imgUrl);
//图片类型
$imgType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
//对应函数
$imageFun = 'imagecreatefrom' . ($imgType == 'jpg' ? 'jpeg' : $imgType);
$i = $imageFun($imgUrl);
//循环色值
$rColorNum=$gColorNum=$bColorNum=$total=0;
for ($x=0;$x<imagesx($i);$x++) {
for ($y=0;$y<imagesy($i);$y++) {
$rgb = imagecolorat($i,$x,$y);
//三通道
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$rColorNum += $r;
$gColorNum += $g;
$bColorNum += $b;
$total++;
}
}
$rgb = array();
$rgb['r'] = round($rColorNum/$total);
$rgb['g'] = round($gColorNum/$total);
$rgb['b'] = round($bColorNum/$total);
return $rgb;
}

*RGB TO HEX
*author cuitengwei
*2014/1/16
*/

function rgb2html($r, $g=-1, $b=-1)
{

if (is_array($r) && sizeof($r) == 3)
list($r, $g, $b) = $r;
$r = intval($r); $g = intval($g);
$b = intval($b);
$r = dechex($r<0?0:($r>255?255:$r));
$g = dechex($g<0?0:($g>255?255:$g));
$b = dechex($b<0?0:($b>255?255:$b));
$color = (strlen($r) < 2?'0':'').$r;
$color .= (strlen($g) < 2?'0':'').$g;
$color .= (strlen($b) < 2?'0':'').$b;
return '#'.$color;
}

*HEX TO RGB
*author cuitengwei
*2014/1/16
*/

function html2rgb($color)
{

if ($color[0] == '#')
$color = substr($color, 1);
if (strlen($color) == 6)
list($r, $g, $b) = array($color[0].$color[1],
$color[2].$color[3],
$color[4].$color[5]);
elseif (strlen($color) == 3)
list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
else
return false;
$r = hexdec($r); $g = hexdec($g); $b = hexdec($b);
return array($r, $g, $b);
}
//使用示例
$imgUrl = "D:/wamp/www/vtest/test.jpg";//图片地址
var_dump(imgColor($imgUrl));
var_dump(rgb2html(245,255,244));
var_dump(html2rgb('#F08098'));