Last active
August 29, 2015 14:06
-
-
Save Leko/65a565382b2db53c8f25 to your computer and use it in GitHub Desktop.
RGBカラーをHueのHSBカラーに変換する関数 PHP版
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* RGBカラーをHueで使用するHSBカラーに変換する | |
* 通常のHSBカラーとの違いはHの値域が0~360ではなく0~65535(16bitカラー)であること | |
* 参考:http://www.technotype.net/tutorial/tutorial.php?fileId=%7BImage%20processing%7D§ionId=%7B-converting-between-rgb-and-hsv-color-space%7D | |
* | |
* @param int $red 赤 | |
* @param int $green 緑 | |
* @param int $blue 青 | |
* @return int[] [$hue, $saturation, $brightness]という値の配列 | |
*/ | |
function rgb2huehsb($red, $green, $blue) | |
{ | |
$max = max([$red, $green, $blue]); | |
$min = min([$red, $green, $blue]); | |
if($max === $min) { | |
$hue = 0; | |
} elseif($max === $red) { | |
$hue = (60 * ($green - $blue) / ($max - $min) + 360) % 360; | |
} elseif($max === $green) { | |
$hue = (60 * ($blue - $red) / ($max - $min) + 120) % 360; | |
} elseif($max === $blue) { | |
$hue = (60 * ($red - $green) / ($max - $min) + 240) % 360; | |
} else { | |
throw new LogicException("想定しない値の組み合わせです:{$red},{$green},{$blue}"); | |
} | |
// 0~360で一度計算して、0~65535に再構成 | |
// FIXME: 色の段階が荒い、未検証 | |
$hue = round(($hue / 360) * 65535); | |
$saturation = round(($max === 0) ? 0 : (255 * (($max - $min) / $max))); | |
$brightness = round($max); | |
return [$hue, $saturation, $brightness]; | |
} | |
$red = 255; | |
$blue = 0; | |
$green = 0; | |
list($hue, $saturation, $brightness) = rgb2huehsb($red, $green, $blue); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment