欢迎访问WDPHP素材源码!今天是2024年03月29日 星期五,时间不早了,早点休息吧!
您好,游客 [ 马上登录 | 注册帐号 | 微信登录 | QQ登录]
当前位置:首页 > 教程 > PHP教程 > 

PHP获取图片主要色值,RGB HEX 转换
栏目分类:PHP教程    发布日期:2019-05-15    浏览次数:3576次     收藏

/*
 *图片主要(三通道)颜色判断
 *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> 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'));


附件有具体代码,欢迎下载并收藏,收藏时记得“赞”哦!

相关热词:

源码 模板 特效 素材 资源 教程 站长