Detect main colors in an image with PHP Detect main colors in an image with PHP php php

Detect main colors in an image with PHP


Here's exactly what you're looking for in PHP: https://github.com/thephpleague/color-extractor

Example :

use League\ColorExtractor\Palette;$palette = Palette::fromFilename('some/image.png');$topEightColors = $palette->getMostUsedColors(8);


This is my simple method to get the main color of an image

$image=imagecreatefromjpeg('image.jpg');$thumb=imagecreatetruecolor(1,1);imagecopyresampled($thumb,$image,0,0,0,0,1,1,imagesx($image),imagesy($image));$mainColor=strtoupper(dechex(imagecolorat($thumb,0,0)));echo $mainColor;


You need to scale down the picture and you will get the main colors of the picture. If you need 4 colors in the pallet, scale it down to about 8x8, 6 colors to about 12x8 and so on...

imagecopyresized for scaled down image then check every pixels and store them in array imagecolorat($image,px,py)

Try this out

<?php// EXAMPLE PICTURE$url='https://www.nordoff-robbins.org.uk/sites/default/files/google.jpg';//var_dump(getColorPallet($url));echoColors(getColorPallet($url));function echoColors($pallet){ // OUTPUT COLORSBAR    foreach ($pallet as $key=>$val)        echo '<div style="display:inline-block;width:50px;height:20px;background:#'.$val.'"> </div>';}function getColorPallet($imageURL, $palletSize=[16,8]){ // GET PALLET FROM IMAGE PLAY WITH INPUT PALLET SIZE    // SIMPLE CHECK INPUT VALUES    if(!$imageURL) return false;    // IN THIS EXEMPLE WE CREATE PALLET FROM JPG IMAGE    $img = imagecreatefromjpeg($imageURL);    // SCALE DOWN IMAGE    $imgSizes=getimagesize($imageURL);    $resizedImg=imagecreatetruecolor($palletSize[0],$palletSize[1]);    imagecopyresized($resizedImg, $img , 0, 0 , 0, 0, $palletSize[0], $palletSize[1], $imgSizes[0], $imgSizes[1]);    imagedestroy($img);    //CHECK IMAGE    /*header("Content-type: image/png");    imagepng($resizedImg);    die();*/    //GET COLORS IN ARRAY    $colors=[];    for($i=0;$i<$palletSize[1];$i++)        for($j=0;$j<$palletSize[0];$j++)            $colors[]=dechex(imagecolorat($resizedImg,$j,$i));    imagedestroy($resizedImg);    //REMOVE DUPLICATES    $colors= array_unique($colors);    return $colors;}?>

Works perfect for me.