Skip to content

Instantly share code, notes, and snippets.

@AlekVolsk
Last active November 7, 2021 21:12
Show Gist options
  • Save AlekVolsk/a2137cb9353d5e43b327ab2dc20a447d to your computer and use it in GitHub Desktop.
Save AlekVolsk/a2137cb9353d5e43b327ab2dc20a447d to your computer and use it in GitHub Desktop.
Get Dominant & Сontrast color
<?php
/**
* getDominantColor
* Получение доминантного цвета. Функция требует наличия библиотеки GD.
*
* @param string $fname полный путь к файлу относительно сервера
* @param bool $skipBlackAndWhite пропускать чисто белый и чисто чёрный тона
* @return array
*/
function getDominantColor($fname, $skipBlackAndWhite = false, $default = ['r' => 0, 'g' => 0, 'b' => 0])
{
if (!file_exists($fname)) {
return $default;
}
$info = getimagesize($fname);
if ($info === false) {
return $default;
}
$type = image_type_to_extension($info[2], false);
if ($type === false) {
return $default;
}
$func = 'imagecreatefrom' . $type;
if (!function_exists($func)) {
return $default;
}
$im = $func($fname);
$imgw = imagesx($im);
$imgh = imagesy($im);
$c = 0;
$result = ['r' => 0, 'g' => 0, 'b' => 0];
for ($i = 0; $i < $imgw; $i++) {
for ($j = 0; $j < $imgh; $j++) {
$rgb = imagecolorat($im, $i, $j);
if ($skipBlackAndWhite && ($rgb == 0 || $rgb == 16777215)) {
continue;
}
$result['r'] += ($rgb >> 16) & 0xFF;
$result['g'] += ($rgb >> 8) & 0xFF;
$result['b'] += $rgb & 0xFF;
$c++;
}
}
$result['r'] = floor($result['r'] / $c);
$result['g'] = floor($result['g'] / $c);
$result['b'] = floor($result['b'] / $c);
return $result;
}
/**
* getContrastColor
* Получение цвета, наиболее контрастного к базовому
*
* @param string $baseColor базовый цвет
* @param string $darkColor тёмный вариант контрастного
* @param string $lightColor светлый вариант контрастного
* @return string $darkColor|$lightColor
*/
function getContrastColor($baseColor, $darkColor = '#000', $lightColor = '#fff')
{
if (strpos($baseColor, '#') === 0) {
$baseColor = substr($baseColor, 1, 6);
}
$l = strlen($baseColor) / 3;
$r = hexdec(substr($baseColor, 0, $l));
$g = hexdec(substr($baseColor, $l, $l));
$b = hexdec(substr($baseColor, $l + $l, $l));
$yiq = (($r * 299) + ($g * 587) + ($b * 114)) / 1000;
return ($yiq >= 128) ? $darkColor : $lightColor;
}
/**
* rgbToHex
* Формирование строки цвета из rgba-переменных
*
* @param int $red
* @param int $green
* @param int $blue
* @param float $alpha
* @return string
*/
function rgbToHex($red, $green, $blue, $alpha = null)
{
$result = '#';
foreach ([$red, $green, $blue] as $row) {
$result .= str_pad(dechex($row), 2, '0', STR_PAD_LEFT);
}
if (!is_null($alpha)) {
$alpha = floor(255 - (255 * ($alpha / 127)));
$result .= str_pad(dechex($alpha), 2, '0', STR_PAD_LEFT);
}
return $result;
}
@AlekVolsk
Copy link
Author

Result of work / Результат работы

screen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment