PHP image border color detection algorithm

I am trying to find a way to get border color from an image using php

I tried to use this code, but this algorathim gives me all the colors in any image.

 <?php 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; } $img = @imagecreatefromjpeg($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('rmnp8.jpg', 10, 4); echo "<table>\n"; foreach($palette as $color) { echo "<tr><td style='background-color:#$color;width:2em;'>&nbsp;</td><td>#$color</td></tr>\n"; } echo "</table>\n"; 

In addition, I am trying to use this to create a design like these projects.

firstsecond

+4
source share
1 answer

The reason you get all the colors in the image is because you use a nested loop to iterate over the pixels in the image. Instead, you should use two consecutive loops: one for checking horizontal boundaries, and the other for checking vertical ones, so your loop code will become something like this:

 function checkColorAt(&$img, $x, $y, &$colors) { $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; } } $colors = array(); for($x = 0; $x < $size[0]; $x += $granularity) { checkColorAt(&$img, $x, $0, &$colors); checkColorAt(&$img, $x, $size[1] - 1, &$colors); } for($y = 0; $y < $size[1]; $y += $granularity) { checkColorAt(&$img, $0, $y, &$colors); checkColorAt(&$img, $size[0] - 1, $y, &$colors); } 
+4
source

All Articles