Detect main colors in an image with PHP

前端 未结 7 2151
走了就别回头了
走了就别回头了 2020-11-27 12:05

I am trying to replicate the functionality that Dribbble.com does with detecting the predominant colors in an Image. In the image below you can see a screenshot from Dribbb

7条回答
  •  自闭症患者
    2020-11-27 12:19

    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

    $val)
            echo '
    '; } 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.

提交回复
热议问题