Detección de colores para una imagen usando PHP
¿Cómo puedo detectar los 2 colores principales de una imagen en PHP?
Por ejemplo tengo esta imagen:
Esta función/proceso de retorno: 0000FF o azul y FFFF00 o AMARILLO
Gracias
25
Author: Tech4Wilco, 2011-10-11
2 answers
Aquí hay un script que le dará la lista:
function detectColors($image, $num, $level = 5) {
$level = (int)$level;
$palette = array();
$size = getimagesize($image);
if(!$size) {
return FALSE;
}
switch($size['mime']) {
case 'image/jpeg':
$img = imagecreatefromjpeg($image);
break;
case 'image/png':
$img = imagecreatefrompng($image);
break;
case 'image/gif':
$img = imagecreatefromgif($image);
break;
default:
return FALSE;
}
if(!$img) {
return FALSE;
}
for($i = 0; $i < $size[0]; $i += $level) {
for($j = 0; $j < $size[1]; $j += $level) {
$thisColor = imagecolorat($img, $i, $j);
$rgb = imagecolorsforindex($img, $thisColor);
$color = sprintf('%02X%02X%02X', (round(round(($rgb['red'] / 0x33)) * 0x33)), round(round(($rgb['green'] / 0x33)) * 0x33), round(round(($rgb['blue'] / 0x33)) * 0x33));
$palette[$color] = isset($palette[$color]) ? ++$palette[$color] : 1;
}
}
arsort($palette);
return array_slice(array_keys($palette), 0, $num);
}
$img = 'icon.png';
$palette = detectColors($img, 6, 1);
echo '<img src="' . $img . '" />';
echo '<table>';
foreach($palette as $color) {
echo '<tr><td style="background:#' . $color . '; width:36px;"></td><td>#' . $color . '</td></tr>';
}
echo '</table>';
21
Author: rcs20,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-02 14:42:17
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-02 14:42:17
Si está de acuerdo en llamar a una utilidad externa, Imagemagick puede generar un histograma para usted. Probablemente va a ser mucho más rápido que una implementación de PHP.
Básicamente, este comando le da una lista de colores, ordenados por la mayoría dominante primero:
convert 'http://i.stack.imgur.com/J2txV.png' -format %c histogram:info:-|sort -r
Es posible que desee asignar la imagen a una paleta fija primero ("Redondear" los colores). Esto es lo que uso:
convert 'http://i.stack.imgur.com/J2txV.png' -modulate 100,200,100 -remap 'http://i.stack.imgur.com/GvTqB.png' -format %c histogram:info:-|sort -r
0
Author: troelskn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-04 10:19:48
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-04 10:19:48