Skip to content

Instantly share code, notes, and snippets.

@Leko
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Leko/65a565382b2db53c8f25 to your computer and use it in GitHub Desktop.
Save Leko/65a565382b2db53c8f25 to your computer and use it in GitHub Desktop.
RGBカラーをHueのHSBカラーに変換する関数 PHP版
<?php
/**
* RGBカラーをHueで使用するHSBカラーに変換する
* 通常のHSBカラーとの違いはHの値域が0~360ではなく0~65535(16bitカラー)であること
* 参考:http://www.technotype.net/tutorial/tutorial.php?fileId=%7BImage%20processing%7D&sectionId=%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