在PHP中查找图像边框颜色的算法 [英] Algorithm to find border color of an image in PHP
本文介绍了在PHP中查找图像边框颜色的算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试找到一种使用php
I am trying to find a way to get a border color from an image using php
我尝试使用此代码,但是此algorathim为我提供了任何图像中的所有颜色.
I have tried to use this code, but this algorathim gives me all 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;'> </td><td>#$color</td></tr>\n";
}
echo "</table>\n";
此外,我正在尝试使用它来构建像这些设计这样的设计.
Also, I am trying to use this in order to build a design like these designs.
推荐答案
之所以要获取图像中的所有颜色,是因为您使用嵌套循环来迭代图像中的像素.相反,您应该使用两个顺序循环:一个检查水平边框,另一个检查垂直边框,因此您的循环代码将变成这样:
The reason you're getting all colours in an image is because you're using a nested loop to iterate over pixels in the image. Instead, you should use two sequential loops: one to check horizontal borders and the other to check 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);
}
这篇关于在PHP中查找图像边框颜色的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文