0
I’m using a PHP function to extract the main colors from an image I found in a question well-known in the OR.
How I separate the values that are listed within the foreach?
When they are listed not to determines where they have to appear, the function only generates a list of all colors, the function has how to determine the quantity but has no way to specify where each color has to appear.
I want to apply each color in a specific location.
Example:
I’ll consult two colors only, to display so:
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>";
}
Wow, so simple and I breaking the head kkk, thank you so much.
– Vitor Hugo