用户
 找回密码
 入住 CI 中国社区
搜索
查看: 2329|回复: 1
收起左侧

[Web] 获得图像的主要颜色算法

[复制链接]
发表于 2014-9-21 16:12:53 | 显示全部楼层 |阅读模式
在这个网站看到的
http://veerle.duoh.com/inspiration

感觉效果很好啊

想试着自己做一下

tp社区有人贴出了下面的算法

好像大家的做法基本都是这样

但是我测试的结果 却没有达到上面这个网站的效果

使用很明显的一幅图像测试 得到的颜色明显有偏差

算法如下

PHP复制代码
 
/*
 * 图片主要(三通道)颜色判断
 */

if ( ! function_exists('image_color'))
{
        function image_color($image)
        {
            $imageInfo = getimagesize($image);
            //图片类型
            $imgType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
            //对应函数
            $imageFun = 'imagecreatefrom' . ($imgType == 'jpg' ? 'jpeg' : $imgType);
            $i = $imageFun($image);
            //循环色值
            $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;
        }
}
 
 
复制代码






发表于 2015-1-6 15:47:00 | 显示全部楼层
打发对方答复打发

本版积分规则