function calculate_avg_color($iconFile) { $palette = colorPalette($iconFile, 4, 4); if (is_array($palette)) { foreach ($palette as $p) { $hsl = rgb2hsl(_color_unpack("#{$p}")); if ($hsl[1] > 0.25 && $hsl[2] > 0.25 && !($hsl[0] >= 0 && $hsl[0] < 0.01 && $hsl[1] < 0.01) && !($hsl[0] >= 0 && $hsl[0] < 0.01 && $hsl[2] > 0.99)) { return _color_pack(hsl2rgb($hsl)); } } } return ''; }
<?php function colorPalette($imageFile) { $size = @getimagesize($imageFile); if ($size === false) { user_error("Unable to get image size data"); return false; } $img = @imagecreatefromstring(file_get_contents($imageFile)); if (!$img) { user_error("Unable to open image file"); return false; } $thisColor = imagecolorat($img, 5, 5); $rgb = imagecolorsforindex($img, $thisColor); $red = round(round($rgb['red'] / 0x33) * 0x33); $green = round(round($rgb['green'] / 0x33) * 0x33); $blue = round(round($rgb['blue'] / 0x33) * 0x33); $thisRGB = sprintf('%02X%02X%02X', $red, $green, $blue); return $thisRGB; } if ($_POST) { $url = $_POST['url']; $color = colorPalette($url, 10, 4); echo $color; }
} if (!$img) { user_error("Unable to open image file"); return false; } for ($x = 0; $x < $size[0]; $x += $granularity) { for ($y = 0; $y < $size[1]; $y += $granularity) { $thisColor = imagecolorat($img, $x, $y); $rgb = imagecolorsforindex($img, $thisColor); $red = round(round($rgb['red'] / 0x33) * 0x33); $green = round(round($rgb['green'] / 0x33) * 0x33); $blue = round(round($rgb['blue'] / 0x33) * 0x33); $thisRGB = sprintf('%02X%02X%02X', $red, $green, $blue); if (array_key_exists($thisRGB, $colors)) { $colors[$thisRGB]++; } else { $colors[$thisRGB] = 1; } } } arsort($colors); return array_slice(array_keys($colors), 0, $numColors); } $pic = "med.jpg"; $palette = colorPalette($pic, 8, 10); sort($palette, SORT_NUMERIC); echo "<img src=\"" . $pic . "\" />"; foreach ($palette as $color) { $css = "display: inline-block; height: 100px; width: 100px; background: #" . $color . ";"; echo "<span style=\"{$css}\"></span>"; }