I'm using a function in PHP to extract the main colors of an image I found in a old question in SO .
How do I separate the values that are listed within the foreach?
When they are listed do not determine where they have to appear, the function only generates a list with all colors, in the function has as determines the quantity but can not specify where each color has to appear.
I want to apply each color to a specific location.
Example:
I'll query two colors only, to display like this:
echo "<div style='width:20px;height:20px;background-image:linear-gradient(90deg, #$color1 40%, #$color2 100%)'></div>";
In the above example I show the first color in $ color1, the second in color2
Function:
<?php
# https://stackoverflow.com/a/3468588/9537649
function colorPalette($imageFile, $numColors, $granularity = 5) {
$granularity = max(1, abs((int)$granularity));
$colors = array();
$size = @getimagesize($imageFile);
if($size === false)
{
user_error("Unable to get image size data");
return false;
}
// Carrega somente imagens jpg
//$img = @imagecreatefromjpeg($imageFile);
// Carrega 'qualquer' tipo de imagem
$img = @imagecreatefromstring(file_get_contents($imageFile));
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);
}
// sample usage:
$palette = colorPalette('image.jpg', 2 /* 2 e quantidade de cores */ , 4 /* o 4 não sei bem o que e mas acredito que seja a precisão das cores*/);
foreach($palette as $color) {
// As cores são listadas com o $color
echo "<div style='width:20px;height:20px;background-image:linear-gradient(90deg, #$color 40%, #$color 100%)'></div>";
}