thinkphp3.2 图片平均颜色值

public 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颜色值转为16进制
public 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;
     }

 

//RGB转hsv
//hsv的v貌似是用来判断明暗的,我用这个是为了图片的字体水印灵活使用黑白两色
function RGB_TO_HSV ($R, $G, $B)  // RGB Values:Number 0-255
{                                 // HSV Results:Number 0-1
   $HSL = array();
   $var_R = ($R / 255);
   $var_G = ($G / 255);
   $var_B = ($B / 255);
   $var_Min = min($var_R, $var_G, $var_B);
   $var_Max = max($var_R, $var_G, $var_B);
   $del_Max = $var_Max - $var_Min;
   $V = $var_Max;
   if ($del_Max == 0)
   {
      $H = 0;
      $S = 0;
   }
   else
     {
      $S = $del_Max / $var_Max;
      $del_R = ( ( ( $var_Max - $var_R ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
      $del_G = ( ( ( $var_Max - $var_G ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
      $del_B = ( ( ( $var_Max - $var_B ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
      if      ($var_R == $var_Max) $H = $del_B - $del_G;
      else if ($var_G == $var_Max) $H = ( 1 / 3 ) + $del_R - $del_B;
      else if ($var_B == $var_Max) $H = ( 2 / 3 ) + $del_G - $del_R;
      if ($H<0) $H++;
      if ($H>1) $H--;
   }
   $HSL['H'] = $H;
   $HSL['S'] = $S;
   $HSL['V'] = $V;
   return $HSL;
}

 

posted @ 2018-04-12 17:35  西瓜霜  阅读(291)  评论(0编辑  收藏  举报