PHP获取图片主要色值

PHP获取图片主要色值

<?php
/*
 *图片主要(三通道)颜色判断
 *author cuitengwei
 *2014/1/16
 */
function imgColor($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'));

转载自:http://www.thinkphp.cn/extend/524.html

共有 0 条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注