PHP 手册中有如下说明:
imagecolorat
(PHP 4, PHP 5)
imagecolorat — Get the index of the color of a pixel
<?php
$im = imagecreatefrompng ( “php.png” );
$rgb = imagecolorat ( $im , 10 , 15 );
$r = ( $rgb >> 16 ) & 0xFF ;
$g = ( $rgb >> 8 ) & 0xFF ;
$b = $rgb & 0xFF ;
var_dump ( $r , $g , $b );
?>
于是可以写一个专门的处理函数:
function getImageMainColor($strUrl) {
$imageInfo = getimagesize($strUrl);
//图片类型
$imgType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
//对应函数
$imageFun = ‘imagecreatefrom’ . ($imgType == ‘jpg’ ? ‘jpeg’ : $imgType);
$i = $imageFun($strUrl);
//循环色值
$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;
}