Home >php教程 >php手册 >php如何识别图片的主颜色

php如何识别图片的主颜色

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-06 20:14:181779browse

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 = $rg

PHP 手册中有如下说明:

imagecolorat

(PHP 4, PHP 5)

imagecolorat — Get the index of the color of a pixel

$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

        for ($y=0;$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;

 }

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn