Drakkhis's post in Troubble with categorizing colors by RGB was marked as the answer
May 16, 2022
<?php
include(dirname( __DIR__ ,1) . "/PDO_db_config.php");
function hexToRgb($hex) {
$hex = str_replace('#', '', $hex);
$length = strlen($hex);
$r = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
$g = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
$b = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
return $r.",".$g.",".$b;
}
function hexToHsl($hex) {
$hex = str_replace('#', '', $hex);
$hex = array($hex[0].$hex[1], $hex[2].$hex[3], $hex[4].$hex[5]);
$rgb = array_map(function($part) {
return hexdec($part) / 255;
}, $hex);
$max = max($rgb);
$min = min($rgb);
$l = ($max + $min) / 2;
if ($max == $min) {
$h = $s = 0;
} else {
$diff = $max - $min;
$s = $l > 0.5 ? $diff / (2 - $max - $min) : $diff / ($max + $min);
switch($max) {
case $rgb[0]:
$h = ($rgb[1] - $rgb[2]) / $diff + ($rgb[1] < $rgb[2] ? 6 : 0);
break;
case $rgb[1]:
$h = ($rgb[2] - $rgb[0]) / $diff + 2;
break;
case $rgb[2]:
$h = ($rgb[0] - $rgb[1]) / $diff + 4;
break;
}
$h /= 6;
}
return array(floor($h*360), floor($s*100), floor($l*100));
}
function getcolorname($mycolor) {
$colors = array(
"magenta" =>array(330,0,0),
"blue" =>array(270,0,0),
"cyan" =>array(210,0,0),
"green" =>array(150,0,0),
"yellow" =>array(90,0,0),
"red" =>array(30,0,0)
);
$tmpname = "red";
foreach($colors as $colorname => $colorset) {
if ($mycolor[0] < $colorset[0]) $tmpname = $colorname;
if ($mycolor[0] == 0 && $mycolor[1] == 0) $tmpname = "grey";
}
return $tmpname;
}
$sql = $pdo->prepare("SELECT * FROM colors");
$sql->execute();
foreach ($sql as $data)
{
$RGB = hexToRgb($data['HEX']);
$arry = explode(',', $RGB);
$DEC = "<".round(($arry[0]/255),3).",".round(($arry[1]/255),3).",".round(($arry[2]/255),3).">";
$HSL = implode(',', hexToHsl($data['HEX']));
$color = getcolorname(hexToHsl($data['HEX']));
$sql2 = $pdo->prepare("UPDATE `colors` SET `category` = :CAT, RGB = :RGB, LSL = :DEC WHERE (`color_ID` = :color_ID)");
$sql2->bindValue(':CAT', $color, PDO::PARAM_STR);
$sql2->bindValue(':RGB', $RGB, PDO::PARAM_STR);
$sql2->bindValue(':DEC', $DEC, PDO::PARAM_STR);
$sql2->bindValue(':color_ID', $data['color_ID'], PDO::PARAM_STR);
$sql2->execute();
}
echo "done5";
It was not adding the correct color category to the color, But I switched to using HSL instead of RGB to categorize it and got it working