2015-10-23

[PHP] 從 RGB 轉換到 HSB

HSB(HSV)通過色相/飽和度/亮度三要素來表達顏色。
  • H(Hue):表示颜色的類型 (例如红色,绿色或者黄色),取值範圍為 0 ~ 360,其中每一个值代表一種顏色
  • S(Saturation):顏色的飽和度從 0 到 1,有时候也稱為纯度 (0 表示灰度圖,1 表示纯的顏色)
  • B(Brightness or Value):顏色的明亮程度從 0 到 1 (0 表示黑色,1 表示特定飽和度的顏色)

function rgb2hsb($rgb) {
    $red   = max(0, min(255, $rgb['red']));
    $green = max(0, min(255, $rgb['green']));
    $blue  = max(0, min(255, $rgb['blue']));

    $max = max($red, $green, $blue);
    $min = min($red, $green, $blue);
    $delta = $max - $min;

    $b = $max / 255;
    $s = $max == 0 ? 0 : $delta / $max;

    $h = 0;
    if ($delta == 0) {
        $h = 0;
    } else if ($max == $red && $green >= $blue) {
        $h = 0   + 60 * ($green - $blue) / $delta;
    } else if ($max == $red && $green < $blue) {
        $h = 360 + 60 * ($green - $blue) / $delta;
    } else if ($max == $green) {
        $h = 120 + 60 * ($blue - $red) / $delta;
    } else if ($max == $blue) {
        $h = 240 + 60 * ($red - $green) / $delta;
    }

    return array('hue' => fmod($h, 360), 'saturation' => $s, 'brightness' => $b);
}



function hsb2rgb($hsb) {
    $h = $hsb['hue'];
    $s = max(0, min(1, $hsb['saturation']));
    $b = max(0, min(1, $hsb['brightness']));

    $h = fmod($h, 360);
    if($h < 0){ $h += 360; }

    $i = ($h / 60) % 6;
    $f = ($h / 60) - $i;
    $p = $b * (1 - $s);
    $q = $b * (1 - $f * $s);
    $t = $b * (1 - (1 - $f) * $s);

    $p = intval(round(255 * $p));  
    $q = intval(round(255 * $q));
    $t = intval(round(255 * $t));
    $b = intval(round(255 * $bri));
    
    switch ($i) {
        case 0: return array('red' => $b, 'green' => $t, 'blue' => $p);
        case 1: return array('red' => $q, 'green' => $b, 'blue' => $p);
        case 2: return array('red' => $p, 'green' => $b, 'blue' => $t);
        case 3: return array('red' => $p, 'green' => $q, 'blue' => $b);
        case 4: return array('red' => $t, 'green' => $p, 'blue' => $b);
        case 5: return array('red' => $b, 'green' => $p, 'blue' => $q);
        default: return array('red' => 0, 'green' => 0, 'blue' => 0);
    }
}

0 回應: